【问题标题】:RestTemplate & multipart/form-data responseRestTemplate & multipart/form-data 响应
【发布时间】:2021-04-22 01:29:39
【问题描述】:

我需要使用 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 之间的表单数据),但它仍然不起作用,因为根据官方文档,这个转换器无法读取多部分/form-data(只写): https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/http/converter/FormHttpMessageConverter.html

这个端点可以通过 Postman 正常工作,返回 JSON 和 File 部分,所以我想知道我缺少哪种魔法才能使用 RestTemplate 使其工作。

是否可以编写一个 REST 客户端来处理 multipart/form-data 响应,如果可以,应该使用哪个转换器来处理此类消息,我是否必须编写自定义 HttpMessageConverter

【问题讨论】:

  • 我现在也有同样的问题。您已经有解决方案了吗?
  • 不。我们使用了一个包含所有必要数据的自定义类,并为它编写了一个自定义 HttpMessageConverter。

标签: java spring multipartform-data resttemplate


【解决方案1】:

我遇到了同样的情况,写了一个简单的例子(MultipartMessageConverter)。此示例允许将请求(资源和 JSON)转换为一个 DTO 模型,正如您可以在测试中看到的那样。一个模型可以包含资源

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

【讨论】:

    猜你喜欢
    • 2020-07-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-17
    • 2015-09-19
    • 2013-12-10
    相关资源
    最近更新 更多