Apache HttpClient with CookieStore (cookie support) in Java

In java many time we need to make a request with cookies support. For example, if a REST service is configured to manage session using cookie session or cookie-based session key then we need to use HTTP client with cookie support.

For this Apache HttpClient client provides HttpClientBuilder Class, CookieStore interface and BasicCookieStore. Using these we can create http client with cookie support.

Java HttpClient with cookie support example:

public class HttpClientCookiExample {
	// Use custom cookie store if necessary.
	static CookieStore cookieStore;

	public final static void main(String[] args) throws Exception {
		cookieStore = new BasicCookieStore();

		// Create HttpClient using cookie store
		try (CloseableHttpClient httpclient = HttpClients.custom().setDefaultCookieStore(cookieStore).build()) {
			HttpGet httpget = new HttpGet("https://google.co.in");

			System.out.println("Executing request " + httpget.getRequestLine());
			try (CloseableHttpResponse response = httpclient.execute(httpget)) {
				System.out.println("----------------------------------------");
				System.out.println(response.getStatusLine());

				// Get hold of the response entity
				HttpEntity entity = response.getEntity();

				// If the response does not enclose an entity, there is no need
				// to bother about connection release
				if (entity != null) {
					try (InputStream inStream = entity.getContent()) {
						inStream.read();
						// do something useful with the response
					} catch (IOException ex) {
						// In case of an IOException the connection will be released
						// back to the connection manager automatically
						throw ex;
					}
				}

				List cookies = cookieStore.getCookies();
				for (Cookie cookie : cookies) {
					// Can access over attributes of cookie
					System.out.println(cookie.getName() + " : " + cookie.getValue());
				}

			}
		}
	}
}

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.