Goal: Post Image using RestTemplate
目标:使用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?
还有其他选择吗? POST一个包含base64编码的byte []数组的JSON是一个有效的替代方案吗?
2 个解决方案
#1
9
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);
#2
3
Ended up turning the Bitmap into a byte array and then encoding it to Base64 and then sending it via RestTemplate using Jackson as my serializer.
最后将Bitmap转换为字节数组,然后将其编码为Base64,然后使用Jackson作为我的序列化程序通过RestTemplate发送它。
#1
9
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);
#2
3
Ended up turning the Bitmap into a byte array and then encoding it to Base64 and then sending it via RestTemplate using Jackson as my serializer.
最后将Bitmap转换为字节数组,然后将其编码为Base64,然后使用Jackson作为我的序列化程序通过RestTemplate发送它。