Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Howto use Spring Resttemplate with JSON only

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.

like image 374
Adrian Avatar asked Apr 25 '12 10:04

Adrian


2 Answers

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.

like image 67
axtavt Avatar answered Oct 12 '22 09:10

axtavt


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);
like image 34
AlexGera Avatar answered Oct 12 '22 11:10

AlexGera