简体   繁体   中英

How to frame RestTemplate for request body of type binary of Postman?

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.

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<>(data);

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM