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?
- GC_FOR_ALLOC 是否更“严重"?在调查内存使用情况时? 2022-01-01
- Eclipse 的最佳 XML 编辑器 2022-01-01
- java.lang.IllegalStateException:Bean 名称“类别"的 BindingResult 和普通目标对象都不能用作请求属性 2022-01-01
- 如何指定 CORS 的响应标头? 2022-01-01
- 未找到/usr/local/lib 中的库 2022-01-01
- 获取数字的最后一位 2022-01-01
- 在 Java 中,如何将 String 转换为 char 或将 char 转换 2022-01-01
- 将 Java Swing 桌面应用程序国际化的最佳实践是什么? 2022-01-01
- 如何使 JFrame 背景和 JPanel 透明且仅显示图像 2022-01-01
- 转换 ldap 日期 2022-01-01