如何为Restman二进制类型的请求主体构建RestTemplate? [英] How to frame RestTemplate for request body of type binary of Postman?

查看:216
本文介绍了如何为Restman二进制类型的请求主体构建RestTemplate?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图使用RestTemplate调用第三方服务,但是当我尝试通过Java代码调用该服务时,会引发BadRequest错误。
由于我无法弄清楚如何为API构架Resttemplate,因此我在此请求有关如何为此类请求构架请求正文的建议,还请看看我现有的代码,并帮助我找到找出代码中的错误。

I am trying to call an third party service using RestTemplate.But when I try to call the service through my Java code it is throwing BadRequest Error. Since I could not figure out how to frame the Resttemplate for the API I am requestng here for a suggestions over how to frame request body for such request,kindly also have a look at my existing code and help me out in finding out the errors in code.

邮递员请求的样子:

How the Postman Request looks like:

以下是邮递员中形成的代码段:

Following is the code snippet formed in Postman:

 OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
  .url("")
  .post(null)
  .addHeader("Authorization", "************")
  .addHeader("User-Agent", "PostmanRuntime/7.13.0")
  .addHeader("Accept", "*/*")
  .addHeader("Cache-Control", "no-cache")
  .addHeader("Postman-Token", "**********")
  .addHeader("Host", "**************")
  .addHeader("accept-encoding", "gzip, deflate")
  .addHeader("content-length", "160200")
  .addHeader("Connection", "keep-alive")
  .addHeader("cache-control", "no-cache")
  .build();

Response response = client.newCall(request).execute();

//其中文件的类型为文件

// where file is of type File

LinkedMultiValueMap<String, Object> map = new LinkedMultiValueMap<>();
map.add("file", new ClassPathResource(file));

HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.TEXT_PLAIN);

HttpEntity<LinkedMultiValueMap<String, Object>> requestEntity = new    
HttpEntity<LinkedMultiValueMap<String, Object>>(
                map, headers);
ResponseEntity<String> result = template.get().exchange(
                contextPath.get() + path, HttpMethod.POST, requestEntity,
                String.class);

我想成功调用第三方实体并获得响应。

I would like to call the third part entity successfully and get Response.

推荐答案

使用 ResponseEntity byte [] 类型,没有内容类型:

Use ResponseEntity with byte[] type and without content type:

InputStream inputStream = new ClassPathResource("myFile.jpg").getInputStream();
byte[] data = IOUtils.toByteArray(inputStream);
HttpEntity<byte[]> requestEntity = new HttpEntity<>(IOUtils.toByteArray(in));

restTemplate.exchange("url", HttpMethod.POST, requestEntity , String.class);

这篇关于如何为Restman二进制类型的请求主体构建RestTemplate?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆