Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to post byte array via RestTemplate

Goal: Post Image using RestTemplate

Currently using a variation of this

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 POSTing a JSON that contains a base64 encoded byte[] array a valid alternative?

like image 475
lemon Avatar asked Oct 28 '11 04:10

lemon


1 Answers

Yep, with something like this I guess

If the image is your payload and if you want to tweak the headers you can post it this way :

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);
like image 149
Alex B Avatar answered Sep 19 '22 11:09

Alex B