J F*_*ird 5 rest spring custom-headers resttemplate
我需要发送一个头的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)
Run Code Online (Sandbox Code Playgroud)
我的代码:
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);
Run Code Online (Sandbox Code Playgroud)
调试消息将标头显示为{Content-Type=[application/camiant-msr-v2.0+xml]},这似乎是正确的。我想知道我的请求有什么问题,以及是否有办法查看网络上的请求以进行调试。
小智 5
以下对我有用:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
@Service
public class Http {
@Autowired
private RestTemplate restTemplate;
public String doGet(final String url) throws Exception {
MultiValueMap<String, String> headers = new LinkedMultiValueMap<String, String>();
headers.add(HttpHeaders.USER_AGENT, "Mozilla/5.0");
headers.add(HttpHeaders.ACCEPT_LANGUAGE, "en-US,en;q=0.8");
HttpEntity<?> entity = new HttpEntity<Object>(headers);
HttpEntity<String> response = restTemplate.exchange(url, HttpMethod.GET, entity, String.class);
return response.getBody();
}
}
Run Code Online (Sandbox Code Playgroud)
实际上,要传递的标头应该命名Accept而不是Content-Type,因为它是 GET 方法。但服务器 API 文档以某种方式表示它期望Content-Type,并且来自命令行/Postman 的 API 在 和 上都运行Content-Type良好Accept。我认为是 Java 库阻止了Content-Typeheader 被传递给 GET 请求。
| 归档时间: |
|
| 查看次数: |
21671 次 |
| 最近记录: |