Chapter 3. HTTP Message Conversion

Objects passed to and returned from some REST operations are converted to HTTP requests and from HTTP responses by IHttpMessageConverters. The IHttpMessageConverter interface is shown below to give you a better feel for its functionality.

public interface IHttpMessageConverters
{
  // Indicate whether the given class and media type can be read by this converter.
  bool CanRead(Type type, MediaType mediaType);

  // Indicate whether the given class and media type can be written by this converter.
  bool CanWrite(Type type, MediaType mediaType);

  // Return the list of MediaType objects supported by this converter.
  IList<MediaType>SupportedMediaTypes { get; }

  // Read an object of the given type from the given input message, and returns it.
  T Read<T>(IHttpInputMessage message) where T : class;

  // Write an given object to the given output message.
  void Write(object content, MediaType contentType, IHttpOutputMessage message);
}

Concrete implementations for the main media (mime) types are provided in the framework and most are registered by default with the RestTemplate on the client-side.

Table 3.1. Supported HTTP message converters by Framework

The implementations of IHttpMessageConverters are described in the following sections.
For all converters a default media type is used but can be overridden by setting the SupportedMediaTypes property.

Refer to the API documentation for more information and to unit tests for example scenarios about each converters.

3.1. ByteArrayMessageConverter

Supports all the .NET Framework versions.

An IHttpMessageConverter implementation that can read and write byte arrays from the HTTP request and response.
By default, this converter supports all media types ('*/*'), and writes with a Content-Type of 'application/octet-stream'.

3.2. StringHttpMessageConverter

Supports all the .NET Framework versions.

An IHttpMessageConverter implementation that can read and write Strings from the HTTP request and response.
By default, this converter supports all text media types ('text/*'), and writes with a Content-Type of 'text/plain'.

3.3. FileInfoHttpMessageConverter

[Warning]Warning
[Obsolete since 1.1: use ResourceHttpMessageConverter]

Supports all the .NET Framework versions.

An IHttpMessageConverter implementation that can write file content to the HTTP request.
By default, this converter supports all text media types ('*/*').

A mapping between file extension and mime types is used to determine the Content-Type of written files.
If no Content-Type is available, 'application/octet-stream' is used.

Table 3.2. Default mime mapping registered with the converter
File extension Mime type
.bmpimage/bmp
.jpgimage/jpg
.jpegimage/jpeg
.pdfapplication/pdf
.pngimage/png
.tifimage/tiff
.txttext/plain
.zipapplication/x-zip-compressed

You can override these defaults using the MimeMapping property.

You can also set the Content-Type header directly as shown in the following example with a file upload :

RestTemplate template = new RestTemplate(); // FormHttpMessageConverter is configured by default
IDictionary<string, object> parts = new Dictionary<string, object>();
HttpEntity entity = new HttpEntity(new FileInfo(@"C:\myFile.xls"));
entity.Headers["Content-Type"] = "application/vnd.ms-excel";
parts.Add("file", entity);
template.PostForLocation("http://example.com/myFileUpload", parts);

3.4. ResourceHttpMessageConverter

[Since 1.1]

Supports all the .NET Framework versions.

An IHttpMessageConverter implementation that can read and write IResource content to the HTTP request.
By default, this converter supports all text media types ('*/*').

[Note]The IResource abstraction

The IResource interface contained in the Spring.IO namespace provides a common interface to describe and access data from diverse resource locations.
This abstraction lets you treat the resource System.IO.Stream in a polymorphic and protocol-independent manner...

Several implementations for common resource locations are provided:

  • AssemblyResource: accesses data stored as .NET resources inside an assembly.
    Uri syntax is assembly://<AssemblyName>/<NameSpace>/<ResourceName>

  • FileResource: accesses file system data.
    Uri syntax is file://<filename>

  • StreamResource: a wrapper around a raw System.IO.Stream.
    Uri syntax is not supported.

  • ByteArrayResource: a wrapper around a byte array.
    Uri syntax is not supported.

The necessary elements of the IResource abstraction have been ported from Spring.NET Core project.

A mapping between file extension (when URI syntax is supported) and mime types is used to determine the Content-Type of written files.
If no Content-Type is available, 'application/octet-stream' is used.

Table 3.3. Default mime mapping registered with the converter
File extension Mime type
.bmpimage/bmp
.jpgimage/jpg
.jpegimage/jpeg
.pdfapplication/pdf
.pngimage/png
.tifimage/tiff
.txttext/plain
.zipapplication/x-zip-compressed

You can override these defaults using the MimeMapping property.

You can also set the Content-Type header directly as shown in the following example with a file upload :

RestTemplate template = new RestTemplate(); // FormHttpMessageConverter is configured by default
IDictionary<string, object> parts = new Dictionary<string, object>();
HttpEntity entity = new HttpEntity(new FileResource(@"C:\myFile.xls"));
entity.Headers["Content-Type"] = "application/vnd.ms-excel";
parts.Add("file", entity);
template.PostForLocation("http://example.com/myFileUpload", parts);

3.5. FormHttpMessageConverter

Supports all the .NET Framework versions.

An IHttpMessageConverter implementation that can handle form data from the HTTP request and response.
By default, this converter reads and writes the media type 'application/x-www-form-urlencoded'.
Form data is read from and written into a NameValueCollection.

RestTemplate template = new RestTemplate(); // FormHttpMessageConverter is configured by default
NameValueCollection form = new NameValueCollection();
form.Add("field 1", "value 1");
form.Add("field 2", "value 2");
form.Add("field 2", "value 3");
template.PostForLocation("http://example.com/myForm", form);

This converter also writes multipart form data (i.e. file uploads) defined by the 'multipart/form-data' media type.
Multipart form data is written into an IDictionary<string, object>.

RestTemplate template = new RestTemplate(); // FormHttpMessageConverter is configured by default
IDictionary<string, object> parts = new Dictionary<string, object>();
parts.Add("field 1", "value 1");
parts.Add("file", new FileResource(@"C:\myFile.jpg"));
template.PostForLocation("http://example.com/myFileUpload", parts);


When writing multipart, this converter uses other IHttpMessageConverter to write the respective MIME parts.
By default, basic converters StringHttpMessageConverter and ResourceHttpMessageConverter are registered to support String and IResource part types. These can be overridden by setting the PartConverters property.

3.6. XmlDocumentHttpMessageConverter

Supports .NET Framework 2.0, 3.5, 4.0 and .NET Compact Framework 3.5.

An IHttpMessageConverter implementation that can read and write XML using the .NET Framework class XmlDocument.
By default, this converter supports media types 'text/xml', 'application/xml', and 'application/*-xml'.

3.7. XElementHttpMessageConverter

Supports .NET Framework 3.5, 4.0, .NET Compact Framework 3.5 and Windows Phone.
Supports Silverlight using Spring.Http.Converters.Xml.Linq.dll.

An IHttpMessageConverter implementation that can read and write XML using the .NET Framework class XElement (Linq to Xml support).
By default, this converter supports media types 'text/xml', 'application/xml', and 'application/*-xml'.

3.7.1. Silverlight support

This converter requires a reference to System.Xml.Linq.dll which is not part of the runtime installed with the Silverlight plug-in.
The dll is included with the SDK, and will be packaged into the Xap file downloaded by the client.
To optimize weight of the Spring.Rest.dll file, XElementHttpMessageConverter is available as an external dll Spring.Http.Converters.Xml.Linq.dll.

Taking as an example the RestSilverlightQuickstart, the XAP file size increases from 29,5Kb to 76,4Kb using Linq to Xml, hence the importance of providing this converter separately.

To use this converter with the RestTemplate, you will have to add it to the message converters it :

template.MessageConverters.Add(new XElementHttpMessageConverter());

3.8. XmlSerializableHttpMessageConverter

Supports .NET Framework 2.0, 3.5, 4.0, .NET Compact Framework 3.5 and Windows Phone.

An IHttpMessageConverter implementation that can read and write XML from .NET classes.
The converter uses the XmlSerializer .NET Framework class.
By default, this converter supports media types 'text/xml', 'application/xml', and 'application/*-xml'.

3.9. DataContractHttpMessageConverter

Supports .NET Framework 3.5, 4.0, Silverlight and Windows Phone.

An IHttpMessageConverter implementation that can read and write XML from .NET classes.
The converter uses the DataContractSerializer .NET Framework class.
By default, this converter supports media types 'text/xml', 'application/xml', and 'application/*-xml'.

3.10. DataContractJsonHttpMessageConverter

[Since 1.1: Previously named 'JsonHttpMessageConverter']

Supports .NET Framework 3.5, 4.0, Silverlight and Windows Phone.

An IHttpMessageConverter implementation that can read and write JSON from .NET classes.
The converter uses the DataContractJsonSerializer .NET Framework class.
By default, this converter supports media type 'application/json'.

3.11. NJsonHttpMessageConverter

Supports all the .NET Framework versions using Spring.Http.Converters.NJson.dll.

An IHttpMessageConverter implementation that can read and write JSON using the Json.NET (Newtonsoft.Json) library.
By default, this converter supports media type 'application/json'.

Unlike DataContractJsonSerializer .NET Framework class used by DataContractJsonHttpMessageConverter, this library supports getting/setting values from JSON directly, without the need to deserialize/serialize to a .NET class.

To use this converter with the RestTemplate, you will have to add it to the message converters list :

template.MessageConverters.Add(new NJsonHttpMessageConverter());

3.12. SpringJsonHttpMessageConverter

[Since 1.1]

Supports all the .NET Framework versions.

An IHttpMessageConverter implementation that can read and write JSON using the Spring.NET lightweight JSON implementation.
By default, this converter supports media type 'application/json'.

The goal of the Spring.NET JSON support is to remain simple and lightweight. The JSON parsing code is based on the SimpleJson library.

Unlike DataContractJsonSerializer .NET Framework class used by DataContractJsonHttpMessageConverter, this library supports getting/setting values from JSON directly, without the need to deserialize/serialize to a .NET class as shown in the following example:

JsonValue json = JsonValue.Parse(("{\"Message\": \"Hello world!\"}"));
json.GetValue<string>("Message");

To use this converter with the RestTemplate, you must first add it to the message converters list :

template.MessageConverters.Add(new SpringJsonHttpMessageConverter());

See the Windows Phone quick start for an basic example of use and Spring.NET Social projects for more advanced usage.

3.13. Feed converters

Supports .NET Framework 3.5, 4.0.
Supports Silverlight using Spring.Http.Converters.Feed.dll.

3.13.1. Atom10FeedHttpMessageConverter

An IHttpMessageConverter implementation that can read and write Atom feeds using .NET Framework classes SyndicationFeed and SyndicationItem.
By default, this converter supports media type 'application/atom+xml'.

3.13.2. Rss20FeedHttpMessageConverter

An IHttpMessageConverter implementation that can read and write RSS feeds using .NET Framework classes SyndicationFeed and SyndicationItem.
By default, this converter supports media type 'application/rss+xml'.

3.13.3. Silverlight support

These converters require a reference to System.ServiceModel.Syndication.dll which is not part of the runtime intalled with the Silverlight plug-in.
The dll is included with the SDK, and will be packaged into the Xap file downloaded by the client.
To optimize weight of the Spring.Rest.dll file, feed converters are available as an external dll Spring.Http.Converters.Feed.dll.

Taking as an example the RestSilverlightQuickstart, the XAP file size increases from 29,5Ko to 189Kb using feeds, hence the importance of providing these converters separately.

To use these converters with the RestTemplate, you must first add them to the message converters list :

template.MessageConverters.Add(new Atom10FeedHttpMessageConverter());
template.MessageConverters.Add(new Rss20FeedHttpMessageConverter());