Java – why should the resttemplate get response be XML in JSON?
I used resttemplate (org. Springframework. Web. Client. Resttemplate) to struggle with an additional spring behavior without success
I use and always receive XML responses in my hole application below the code, and I parse and evaluate the results
String apiResponse = getRestTemplate().postForObject(url,body,String.class);
However, it is not clear why the server response is in JSON format after execution:
String apiResponse = getRestTemplate().getForObject(url,String.class);
I debug in low-level resttemplate. The content type is XML, but I don't know why the result is in JSON
When I access from the browser, the response is also in XML format, but in apiresponse, I get JSON
I tried many options after reading the spring documentation http://docs.spring.io/spring/docs/3.0.x/api/org/springframework/web/client/RestTemplate.html
He also tried to change the title clearly, but he still couldn't figure it out
I debugged the resttemplate class and noticed that this method always sets 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);
}
}
}
Can you come up with an idea?
Solution
I can solve my problem through RC Your help I will post answers to help others
The problem is that the accept header is automatically set to application / JSON, so I have to change the way I call the service to provide the accept header I want
I changed this:
String response = getRestTemplate().getForObject(url,String.class);
To do this, to make the application work:
// 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();
