11.12. Working with Cookies
Problem
You need to work with a system that uses cookies to store state, and you need to be able to set cookies as well as keep track of cookies set by the server.
Solution
HttpClient
handles cookies automatically. If you
need to keep track of a cookie set by the server, simply use the same
instance of HttpClient
for each request in a
session. If you need to set a cookie, create an instance of
Cookie
, and add it to
HttpState
. The following example sends a
Cookie
to the server:
import
java.io.IOException;import
org.apache.commons.httpclient.Cookie;import
org.apache.commons.httpclient.HttpClient;import
org.apache.commons.httpclient.HttpException;import
org.apache.commons.httpclient.HttpMethod;import
org.apache.commons.httpclient.methods.GetMethod; HttpClient client =new
HttpClient( ); System.out.println( "Making Request without Cookie: " ); makeRequest(client); System.out.println( "Making Request with Cookie: " ); Cookie cookie =new
Cookie(".discursive.com", "test_cookie", "hello", "/", null,false
); client.getState( ).addCookie( cookie ); makeRequest(client);private
static
void
makeRequest(HttpClient client)throws
IOException, HttpException { String url = "http://www.discursive.com/cgi-bin/jccook/cookie_test.cgi"; HttpMethod method =new
GetMethod( url ); client.executeMethod( method ); String response = method.getResponseBodyAsString( ); System.out.println( response ); method.releaseConnection( ); method.recycle( ); }
This example hits a CGI ...
Get Jakarta Commons Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.