Thursday, March 04, 2010

Spring 3 - RestTemplate - Access to Request Headers

The RestTemplate is a recent addition to the Spring framework coming with the Spring @MVC 3.0.x. It provides a RESTful service access mechanism implemented in a way similar to the other Spring template classes. The reference documentation and this bolg provide a good overview of the RestTemplate capabilities.

Unfortunately the current implementation does not provide an easy way to set http request headers with the RestTemplate's GET and POST methods. This is a known issue and is to be resolved in Spring 3.1.

In the meantime you can use the following simple decorator class (RestTemplateExt) that extends the original RestTemplate and provides access to the request http headers via the getRequestHttpHeaders() method.



With this approach you can pre-set some header values with a single RestTemplateExt instance and send them on every http method call. If different header sets are required by the different http methods then you may have to create separate RestTemplateExt instance for each http method.

5 comments:

  1. Hi,

    thanks for the great workaround. Using a delete request with your extension i had a little issue though. If the targetCallBack is null (which is the case if you delete sth.) then it throws a nullpointer exception. You can easily avoid this by adding a nullcheck before calling it:

    request.getHeaders().putAll(headers);
    if (targetRequestCallback != null) {
    targetRequestCallback.doWithRequest(request);
    }

    ReplyDelete
  2. Hi Leonard,
    Thanks for the suggestion.
    Cheers

    ReplyDelete
  3. Hi,
    I don't know what version of Spring didn't let setting headers for RestTemplate requests.
    With version 3.0.5 it's easy using post or put methods, if you pass a HttpEntity as the request object.
    For get and delete, you can use the exchange method.

    Example:

    T body;
    RestTemplate template;

    HttpHeaders headers=new HttpHeaders

    // Set whatever headers you need

    HttpEntity entity=new HttpEntity(body,headers);
    template.postForLocation("url",entity,urlVariables...);
    template.put("url",entity,urlVariables...);
    template.exchange("url",HttpMethod.GET,entity,ResponseType.class,urlVariables...);

    I hope this is useful :)

    ReplyDelete
  4. Hi very good suggestion.

    You can also use an interceptor.
    *Implement ClientHttpRequestInterceptor
    *You can modify the request headers in the overriden intercept method
    *Then execute your request
    *After you have just to setInterceptors on your restTemplate

    ReplyDelete
    Replies
    1. That's right, see: http://svenfila.wordpress.com/2012/01/05/resttemplate-with-custom-http-headers/#comment-80

      Delete