How to send an array of bytes via RestTemplate

Purpose: send an image using RestTemplate

A variant of this is currently being used.

MultiValueMap<String, Object> parts = new LinkedMultiValueMap<String, Object>(); parts.add("field 1", "value 1"); parts.add("file", new ClassPathResource("myFile.jpg")); template.postForLocation("http://example.com/myFileUpload", parts); 

Are there any alternatives? Is a JSON POST connection that contains byte bytes with a base64 byte a valid alternative?

+6
source share
2 answers

Ended up the inclusion of Bitmap in a byte array, and then its encoding to Base64, and then sending it via RestTemplate using Jackson as my serializer.

+3
source

Yes, with something like this, I think

If the image is your payload, and if you want to customize the headers, you can post it like this:

 HttpHeaders headers = new HttpHeaders(); headers.set("Content-Type", "image/jpeg"); InputStream in = new ClassPathResource("myFile.jpg").getInputStream(); HttpEntity<byte[]> entity = new HttpEntity<>(IOUtils.toByteArray(in), headers); template.exchange("http://example.com/myFileUpload", HttpMethod.POST, entity , String.class); 

Otherwise:

 InputStream in = new ClassPathResource("myFile.jpg").getInputStream(); HttpEntity<byte[]> entity = new HttpEntity<>(IOUtils.toByteArray(in)); template.postForEntity("http://example.com/myFileUpload", entity, String.class); 
+8
source

Source: https://habr.com/ru/post/900261/


All Articles