如何为 Postman 二进制类型的请求正文构建 RestTemplate?

How to frame RestTemplate for request body of type binary of Postman?(如何为 Postman 二进制类型的请求正文构建 RestTemplate?)

本文介绍了如何为 Postman 二进制类型的请求正文构建 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:

以下是 Postman 中形成的代码片段:

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.

推荐答案

使用 ResponseEntitybyte[] 类型和不带内容类型:

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

这篇关于如何为 Postman 二进制类型的请求正文构建 RestTemplate?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:如何为 Postman 二进制类型的请求正文构建 RestTemplate?

基础教程推荐