java - 如何将正文添加到具有标头的 SpringBoot RestTemplate Put 请求
问题描述
我的代码使用 restTemplate 来 PUT 请求信息,并使用标头来执行此操作。但是,如何将信息添加到请求的正文中?
在UNIREST中,它会这样做:
HttpResponse<String> response = Unirest.put(apiUrl + "/photos/" + photo.getId()).headers(standardHeaders()).body("{ \"status\": \"" + status + "\" }").asString();
if (response.getStatus() != 200) {
log.error("Status " + response.getStatus() + " returned from CloudCard API when updating photo.");
return null;
}
return new ObjectMapper().readValue(response.getBody(), new TypeReference<Photo>() {
})
-
我目前拥有的代码如下,我想做与上面对 Unirest 所做的相同的事情,而不是使用 restTemplate。
public Photo updateStatus(Photo photo, String status) throws Exception {
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
headers.setContentType(MediaType.APPLICATION_JSON);
headers.set("X-Auth-Token", accessToken);
Photo newPhoto = photo;
newPhoto.setStatus(status);
ResponseEntity<Photo> response = restTemplate.exchange(apiUrl+ "/photos/" + photo.getId(),
HttpMethod.PUT,
new HttpEntity<Photo>(headers),
new ParameterizedTypeReference<Photo>() {},
newPhoto);
return response.getBody();
}
解决方案
推荐阅读
- google-apps-script - Google Apps Script Sheets 功能停止工作,不再工作
- azure - 应用服务未返回具有自定义 TLS 绑定的完整证书链
- c# - C#按字符串过滤对象列表
- reactjs - 在 Next.js 中存储管理 API 令牌的最佳方式是什么?感觉就像在客户端存储它,因为只有 http 的 cookie 是有风险的
- android - Android 应用程序链接不起作用且未出现在 adb dumpsys 中
- java - 在 feign 客户端拦截器中获取请求 url
- pandas - 在单个批次上运行 pandas udf
- python - Python/SQL 中的触发器
- c# - 如何使用 iTextSharp 在 C# 中设置字体大小
- python - 从 N 个 numpy 数组生成相同大小的批次