Resttemplate form/multipart: image + JSON in POST

前端 未结 1 832
梦毁少年i
梦毁少年i 2021-02-14 10:52

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

相关标签:
1条回答
  • 2021-02-14 11:35

    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 HttpMessageConverters

    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);
    
    0 讨论(0)
提交回复
热议问题