首页 > 解决方案 > 如何在 Spring Boot Rest Template 中删除和添加新的 Accept 标头?

问题描述

我正在使用GraphQL服务,如果Accept 标头为text/plain.

它期待接受application/json 所以我尝试覆盖 RestTeamplate 标头。但是,Accept 标头似乎test/plain总是存在在那里。我通过启用 debug( logging.level.org.springframework.web.client.RestTemplate=DEBUG)确认了这一点

安慰

 o.s.web.client.RestTemplate: Accept=[text/plain, application/json, application/*+json, */*]
 o.s.web.client.RestTemplate: Writing [{products(query: "title:tow*", first: 10) {edges {node {id legacyResourceId title}}}}] as "application/graphql"

这是我试图覆盖 Accept 标头的代码

HttpHeaders headers = new HttpHeaders();
RestTemplate restTemplate = new RestTemplate();

headers.add("Content-Type","application/graphql");
headers.setAccept(Collections.singletonList(new MediaType("application","json")));

String content = "{products(query: \"title:tow*\", first: 10) {edges {node {id title}}}}";
HttpEntity<String> requestEntity = new HttpEntity<String>(content, headers);
ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.POST, requestEntity, String.class);

我什至尝试先删除 Accept 标头(headers.remove("Accept"))然后setAccept,但它仍然没有从日志中删除它。

还有什么需要做的吗?

为什么它不从 Accept 标头中删除 text/plain?

为什么我只设置一个选项时在接受中看到多个选项?

标签: spring-bootgraphqlhttp-headersresttemplatehttp-accept-header

解决方案


推荐阅读