How to frame RestTemplate for request body of type binary of Postman?(如何为 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.
推荐答案
使用 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<>(data);
restTemplate.exchange("url", HttpMethod.POST, requestEntity , String.class);
这篇关于如何为 Postman 二进制类型的请求正文构建 RestTemplate?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何为 Postman 二进制类型的请求正文构建 RestTemplate?
基础教程推荐
- Spring Boot Freemarker从2.2.0升级失败 2022-01-01
- 如何使用 Eclipse 检查调试符号状态? 2022-01-01
- 如何对 HashSet 进行排序? 2022-01-01
- 首次使用 Hadoop,MapReduce Job 不运行 Reduce Phase 2022-01-01
- 如何强制对超级方法进行多态调用? 2022-01-01
- 如何在不安装整个 WTP 包的情况下将 Tomcat 8 添加到 Eclipse Kepler 2022-01-01
- 如何使用 Stream 在集合中拆分奇数和偶数以及两者的总和 2022-01-01
- Java 中保存最后 N 个元素的大小受限队列 2022-01-01
- 在螺旋中写一个字符串 2022-01-01
- 由于对所需库 rt.jar 的限制,对类的访问限制? 2022-01-01