您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

如何在Spring RestTemplate请求上设置“ Accept:”标头?

如何在Spring RestTemplate请求上设置“ Accept:”标头?

我建议使用exchange可以接受的方法之一,也可以httpentity为其设置HttpHeaders。(你也可以指定要使用的HTTP方法。)

例如,

RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));

httpentity<String> entity = new httpentity<>("body", headers);

restTemplate.exchange(url, HttpMethod.POST, entity, String.class);

我喜欢这种解决方案,因为它是强类型的。exchange期望一个httpentity

不过,你也可以将其httpentity作为request参数传递给postForObject

httpentity<String> entity = new httpentity<>("body", headers);
restTemplate.postForObject(url, entity, String.class); 

RestTemplate#postForObjectJavadoc中提到了这一点。

该request参数可以是a httpentity,以便向请求中添加其他HTTP标头。

Java 2022/1/1 18:24:57 有484人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶