Accessing Restful services. HTTP Message converters

Registered converters

When accessing to Restful services, the Spring class RestTemplate maintains a list of message converters. This list will be used to marshal objects into the request body, or unmarshalling them from the response. When instantiating the RestTemplate class, it automatically fills a list with several converters:

  • ByteArrayHttpMessageConverter
  • StringHttpMessageConverter
  • ResourceHttpMessageConverter
  • SourceHttpMessageConverter
  • AllEncompassingFormHttpMessageConverter
 
Also, the RestTemplate class may register additional message converters if it finds the required classes on the classpath:
  •  JAXB converter: Converts xml using JAXB2. The Binder class must be found on the classpath. If you are using Java 6, it is no longer necessary as it already comes with the JDK. If you are using Java 5, add the following dependencies:

 

  • Jackson converter: Converts Objects from/to JSON. ObjectMapper and JsonGenerator must exist on the classpath.

 

  •  Atom and RSS feeds converters. The WireFeed class must be present on the classpath.

Serving different content

 The following controller will execute three different operations that will generate xml, String and json content.
JSON content:

Result: JSON. The User class can be serialized/deserialized by the Jackson object mapper.

String content:

 

Result: String. The returned object is a String.

Xavi Padro
XML content:

 

Result: XML. The Car class is annotated with @XmlRootElement
You can also specify the converters that will be used by the RestTemplate. You could, for example, only instantiate the needed converters or register your own message converter:

 

Just take into account that if you serve both json and xml content, you must add the jaxb2 converter before the json converter. Otherwise, regardless of the presence of xml annotations, the xml method response will be handled by the jackson converter and be converted to json. That happens because the HttpEntityRequestCallback inner class of the RestTemplate will use the first converter that can write/read the content.

 

You can get the source code from Github repository.

 

Share it:

Leave a Reply

Your email address will not be published. Required fields are marked *