我在使用 RestTemplate (org.springframework.web.client.RestTemplate) 时遇到了异常的 spring 行为,但没有成功。
我在代码下方的 hole 应用程序中使用,并且总是收到 XML 响应,我解析并评估其结果。
String apiResponse = getRestTemplate().postForObject(url, body, String.class);
但无法弄清楚为什么执行后服务器响应是JSON格式:
String apiResponse = getRestTemplate().getForObject(url, String.class);
我在低级别调试了 RestTemplate,内容类型是 XML,但不知道为什么结果是 JSON。
当我从浏览器访问时,响应也是 XML 格式,但在 apiResponse 中我得到的是 JSON。
阅读 Spring 文档后我尝试了很多选项 http://docs.spring.io/spring/docs/3.0.x/api/org/springframework/web/client/RestTemplate.html
也尝试显式修改标题,但仍然无法弄清楚。
我调试了 RestTemplate 类并注意到此方法始终设置 application/json:
public void doWithRequest(ClientHttpRequest request) throws IOException {
if (responseType != null) {
List<MediaType> allSupportedMediaTypes = new ArrayList<MediaType>();
for (HttpMessageConverter<?> messageConverter : getMessageConverters()) {
if (messageConverter.canRead(responseType, null)) {
List<MediaType> supportedMediaTypes = messageConverter.getSupportedMediaTypes();
for (MediaType supportedMediaType : supportedMediaTypes) {
if (supportedMediaType.getCharSet() != null) {
supportedMediaType =
new MediaType(supportedMediaType.getType(), supportedMediaType.getSubtype());
}
allSupportedMediaTypes.add(supportedMediaType);
}
}
}
if (!allSupportedMediaTypes.isEmpty()) {
MediaType.sortBySpecificity(allSupportedMediaTypes);
if (logger.isDebugEnabled()) {
logger.debug("Setting request Accept header to " + allSupportedMediaTypes);
}
request.getHeaders().setAccept(allSupportedMediaTypes);
}
}
}
你能给个主意吗?
最佳答案
我可以在 RC. 的帮助下解决我的问题。我会发布答案以帮助其他人。
问题是 Accept header 自动设置为 APPLICATION/JSON,所以我不得不更改调用服务的方式以提供我想要的 Accept header 。
我改变了这个:
String response = getRestTemplate().getForObject(url, String.class);
为此,为了使应用程序正常工作:
// Set XML content type explicitly to force response in XML (If not spring gets response in JSON)
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Arrays.asList(MediaType.APPLICATION_XML));
HttpEntity<String> entity = new HttpEntity<String>("parameters", headers);
ResponseEntity<String> response = getRestTemplate().exchange(url, HttpMethod.GET, entity, String.class);
String responseBody = response.getBody();
关于java - 为什么 RestTemplate GET 响应是 JSON 而应该是 XML?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21613416/