I\'m trying to call a rest ws (using resttemplate), that accepts an image and some JSON. However, I don\'t seem to be able to get it running.
The relevant code is as fol
If you want to use ByteArrayResource
, simply register a ResourceHttpMessageConverter
.
If you want to use a byte[]
, simply register a ByteArrayHttpMessageConverter
.
The content type of the image part should be an image type, like image/png
, not application/json
.
You can set each individual part's data type with
HttpHeaders partHeaders = new HttpHeaders();
partHeaders.setContentType(MediaType.IMAGE_PNG);
HttpEntity<ByteArrayResource> bytesPart = new HttpEntity<ByteArrayResource>(bytes, partHeaders);
map.add("file", bytesPart);
Create your RestTemplate
by providing your collection of HttpMessageConverter
s
HttpMessageConverter<Object> jackson = new MappingJackson2HttpMessageConverter();
HttpMessageConverter<Resource> resource = new ResourceHttpMessageConverter();
FormHttpMessageConverter formHttpMessageConverter = new FormHttpMessageConverter();
formHttpMessageConverter.addPartConverter(jackson);
formHttpMessageConverter.addPartConverter(resource); // This is hope driven programming
RestTemplate restTemplate = new RestTemplate(Arrays.asList(jackson, resource, formHttpMessageConverter));
and your outermost HttpEntity
should have a multipart content type
header.setContentType(MediaType.MULTIPART_FORM_DATA);