13

目标:使用 RestTemplate 发布图片

目前使用这个的变体

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); 

有没有其他选择?发布包含 base64 编码的 byte[] 数组的 JSON 是有效的替代方法吗?

4

2 回答 2

15

是的,我猜是这样的

如果图像是您的有效负载并且如果您想调整标题,您可以这样发布:

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);

除此以外 :

InputStream in = new ClassPathResource("myFile.jpg").getInputStream();
HttpEntity<byte[]> entity = new HttpEntity<>(IOUtils.toByteArray(in));
template.postForEntity("http://example.com/myFileUpload", entity, String.class);
于 2014-07-18T13:44:10.713 回答
3

最终将位图转换为字节数组,然后将其编码为 Base64,然后使用 Jackson 作为我的序列化器通过 RestTemplate 发送它。

于 2011-11-04T12:37:54.023 回答