【发布时间】:2016-11-12 03:54:25
【问题描述】:
我需要发送一个带有标题的 GET 请求:Content-Type: application/camiant-msr-v2.0+xml。我期待来自服务器的 XML 响应。我用 Postman 测试了请求和响应,一切都很好。但是当我尝试在 Spring 中使用 RestTemplate 执行此操作时,我总是收到 400 错误请求。 spring 的例外情况是:
Jul 09, 2016 12:53:38 PM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [dispatcherServlet] in context with path [/smp] threw exception [Request processing failed; nested exception is org.springframework.web.client.HttpClientErrorException: 400 Bad Request] with root cause
org.springframework.web.client.HttpClientErrorException: 400 Bad Request
at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:91)
at org.springframework.web.client.RestTemplate.handleResponse(RestTemplate.java:641)
at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:597)
at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:557)
at org.springframework.web.client.RestTemplate.exchange(RestTemplate.java:475)
我的代码:
MultiValueMap<String, String> headers = new LinkedMultiValueMap<String, String>();
headers.add("Content-Type", "application/camiant-msr-v2.0+xml");
HttpEntity<?> entity = new HttpEntity<Object>(headers);
log.debug("request headers: " + entity.getHeaders());
ResponseEntity<String> response = restTemplate.exchange(queryUrl, HttpMethod.GET, entity, String.class);
调试消息将标头显示为{Content-Type=[application/camiant-msr-v2.0+xml]},这似乎是正确的。我想知道我的请求出了什么问题,是否有办法查看在线上的请求以进行调试。
【问题讨论】:
-
如果您要发送 GET,为什么要提供
Content-Type标头?你希望它改为Accept吗? -
@nicholas.hauschild 因为服务器期望,只有提供该标头,我才能获得 XML 响应。
-
@nicholas.hauschild 我有点理解你的意思,但 API 规范这么说,而且 Postman 也能正常工作。
-
@nicholas.hauschild 实际上,将其更改为
Accept对我有用!我认为这是因为 Java 库防止了不规则的使用,例如在 GET 请求中设置Content-Type。非常感谢!
标签: spring rest resttemplate custom-headers