[英]Android RestTemplate post multipart/form-data with utf-8
[英]RestTemplate & multipart/form-data response
我需要使用RestTemplate
编写一个 REST 客户端,它将调用以下端点:
@RequestMapping(value = "/{documentID}", method = RequestMethod.GET, produces = "multipart/form-data")
@ResponseBody
ResponseEntity<MultiValueMap<String, Object>> getDocument(@PathVariable("documentID") long documentID);
此端点构建multipart/form-data
响应,包括文档 ( InputStreamResource
) 和文档的信息 (JSON) 部分。 但是,我收到以下异常:
org.springframework.web.client.UnknownContentTypeException: Could not extract response: no suitable HttpMessageConverter found for response type [interface org.springframework.util.MultiValueMap] and content type [multipart/form-data;boundary=f9yLuCpxZoS4W5lu5iYivlD8fIo28BBMr5PXzu;charset=UTF-8]
我的RestTemplate
中有FormHttpMessageConverter
(应该处理与MultiValueMap
之间的表单数据),但它仍然不起作用,因为根据官方文档,该转换器无法读取 multipart/form-data (仅写入): https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/http/converter/FormHttpMessageConverter.ZFC35FDC70D5FC69D26EZ883A82C7532
这个端点通过 Postman 工作正常,返回 JSON 和 File 部分,所以我想知道我缺少哪种魔法来使它使用RestTemplate
工作。
是否可以编写 REST 客户端来处理multipart/form-data
响应,如果可以,应该为此类消息使用哪个转换器,我是否必须编写自定义HttpMessageConverter
?
我遇到了同样的情况,写了一个简单的例子( MultipartMessageConverter )。 此示例允许将请求(资源和 JSON)转换为一个 DTO model,正如您可以在测试中看到的那样。 一个 model 可以包含资源
RestTemplate restTemplate = new RestTemplate();
restTemplate.getMessageConverters().add(new MultiPartMessageConverter(objectMapper));
final ResponseEntity<ResultModel> responseEntity = restTemplate.getForEntity("http://localhost:" + randomServerPort + "/test", ResultModel.class);
final ResultModel resultModel = responseEntity.getBody();
Assertions.assertNotNull(resultModel);
Assertions.assertEquals(2, resultModel.secondModel.size());
Assertions.assertEquals("Param1.Value", resultModel.firstModel.param1);
Assertions.assertEquals("Param2.Value", resultModel.firstModel.param2);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.