[英]Get InputStream and JSON in RestTemplate Response with postForObject
[英]Why RestTemplate GET response is in JSON when should be in 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<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標頭自動設置為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<String> entity = new HttpEntity<String>("parameters", headers);
ResponseEntity<String> response = getRestTemplate().exchange(url, HttpMethod.GET, entity, String.class);
String responseBody = response.getBody();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.