为什么RestTemplate GET响应是在JSON中应该是XML?
我使用RestTemplate(org.springframework.web.client.RestTemplate)在一个额外的弹簧行为上挣扎但没有成功。
我在代码下面的我的洞应用程序中使用并始终接收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 allSupportedMediaTypes = new ArrayList(); for (HttpMessageConverter messageConverter : getMessageConverters()) { if (messageConverter.canRead(responseType, null)) { List 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头被自动设置为APPLICATION / JSON所以我不得不改变调用服务的方式,以便提供我想要的Accept头。
我改变了这个:
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 entity = new HttpEntity ("parameters", headers); ResponseEntity response = getRestTemplate().exchange(url, HttpMethod.GET, entity, String.class); String responseBody = response.getBody();