Spring in Practice

Willie Wheeler's Spring blog

Sending Cookies With RestTemplate

| Comments

Sometimes it is necessary to send cookies along with requests to a RESTful API. One such example is the JIRA 4.3 API, which requires sending the JSESSIONID to JIRA for session management and authentication purposes. REST purists point out that such usages are not properly RESTful (see http://blog.mikepearce.net/2010/08/24/cookies-and-the-restful-api/ for a good discussion), and indeed the RestTemplate doesn’t directly support sending cookies.

But in the real world, we need to make things work, and so in this quick post I’ll show how to send cookies with RestTemplate.

The first thing to bear in mind is that we implement cookies as HTTP headers: the service uses a Set-Cookie response header to tell the client to set a cookie, and the client uses the Cookie request header for subsequent requests. And RestTemplate certainly supports setting request headers.

Here’s how I’m pulling down an access-controlled RSS feed from JIRA 4.3:

HttpHeaders requestHeaders = new HttpHeaders();
requestHeaders.add("Cookie", "JSESSIONID=" + session.getValue());
HttpEntity requestEntity = new HttpEntity(null, requestHeaders);
ResponseEntity rssResponse = restTemplate.exchange(
Rss rss = rssResponse.getBody();

The trick here is to use the RestTemplate’s exchange() method, as this gives us more control over the request, including request headers. We just encode the cookie as a JSESSIONID=[session ID] request header and send it along.

Have fun!