如何通过 RestTemplate 发布字节数组

2024-05-03

目标:使用 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); 

还有其他选择吗? POST 包含 base64 编码的 byte[] 数组的 JSON 是有效的替代方案吗?


是的,我想有这样的事情

如果图像是您的有效负载并且您想调整标题,您可以通过以下方式发布:

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);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何通过 RestTemplate 发布字节数组 的相关文章

随机推荐