11
votes

I have a rest-service which provides information in XML or JSON. I connect my application to this service with Spring Resttemplate. Unfortunately my responses are all in XML instead of the prefered JSON format. My analysis of the requests is, that Spring Resttemplate sends the request with the following Accept-Header:

Accept: application/xml, text/xml, application/*+xml, application/json

My rest-service response with the first accepted type. This is allways application/xml.

How can I change the Accept-Types so that I only get json responses? Are there some properties for this in the bean-definition of RestTemplate?

I use Spring 3.1 for this.

2

2 Answers

14
votes

You need to set a list of HttpMessageConverters available to RestTemplate in order to override the default one:

 RestTemplate rest = new RestTemplate();
 rest.setMessageConverters(Arrays.asList(new MappingJacksonHttpMessageConverter()));

If you define RestTemplate in XML, do the same thing in XML syntax.

1
votes

Not so clear from the topic if you want to consume JSON only or send. In first case (consuming) you can annotate your Controller with

@RequestMapping(value="/path", headers = "Accept=application/json")

In case of producing you have to for ResponseEntry with contentType:

HttpHeaders headers = new HttpHeaders();
        headers.add("Accept", "application/json");

        ResponseEntity.status(HttpStatus.OK)
                        .contentType(MediaType.APPLICATION_JSON)
                        .headers(headers);