简体   繁体   中英

RestTemplate & multipart/form-data response

I need to write a REST Client using RestTemplate that will call the following endpoint:

@RequestMapping(value = "/{documentID}", method = RequestMethod.GET, produces = "multipart/form-data")
@ResponseBody
ResponseEntity<MultiValueMap<String, Object>> getDocument(@PathVariable("documentID") long documentID);

This endpoint builds multipart/form-data response including a document ( InputStreamResource ) and the document's info (JSON) parts. However, I receive the following exception:

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]

I have FormHttpMessageConverter (that is supposed to process form data to/from a MultiValueMap ) in my RestTemplate , but it still doesn't work because according to the official docs this converter can't read multipart/form-data (only write): https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/http/converter/FormHttpMessageConverter.html

This endpoint works fine via Postman, returning both JSON and File parts, so I'm wondering which kind of magic I'm missing to make it work using RestTemplate .

Is it possible to write a REST client to process multipart/form-data response and if yes, which converter should be used for such messages, do I have to write a custom HttpMessageConverter ?

I collided with the same case and wrote a simple example( MultipartMessageConverter ). This example allows to convert a request(resource and JSON) to one DTO model as you can se in test. A model can consist Resource

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM