URLConnection

Get cookies from HTTP connection

With this example we are going to demonstrate how to get cookies from an HTTP connection in Java. In short, to retrieve cookie information of a URL connection you should

  • Create a URL Object that represents the resource you want to access
  • Use the openConnection() API method of the URL Object to access connection specific parameters for the HTTP request
  • Use the getHeaderFields() API method from the connection Object to get the full list of Name-Value pairs representing the header fields of the specific connection
  • Cookie information should be – if present – under the “Set-Cookie” header field. Several Name-Value pairs may comprise the value of the specific cookie separated by semi-colons

You may get the specific cookie value as shown in the code snippet below.

package com.javacodegeeks.snippets.core;

import java.net.URL;
import java.net.URLConnection;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class GetCookiesFromHTTPConnection {
	
	public static void main(String[] args) throws Exception {
		
		URL url = new URL("http://www.google.com:80");
		URLConnection conn = url.openConnection();

		Map<String, List<String>> headerFields = conn.getHeaderFields();

		Set<String> headerFieldsSet = headerFields.keySet();
		Iterator<String> hearerFieldsIter = headerFieldsSet.iterator();
		
		while (hearerFieldsIter.hasNext()) {
			
			 String headerFieldKey = hearerFieldsIter.next();
			 
			 if ("Set-Cookie".equalsIgnoreCase(headerFieldKey)) {
				 
				 List<String> headerFieldValue = headerFields.get(headerFieldKey);
				 
				 for (String headerValue : headerFieldValue) {
					 
					System.out.println("Cookie Found...");
					 
					String[] fields = headerValue.split(";\s*");

					String cookieValue = fields[0];
					String expires = null;
					String path = null;
					String domain = null;
					boolean secure = false;
					
					// Parse each field
					for (int j = 1; j < fields.length; j++) {
						if ("secure".equalsIgnoreCase(fields[j])) {
							secure = true;
						}
						else if (fields[j].indexOf('=') > 0) {
							String[] f = fields[j].split("=");
							if ("expires".equalsIgnoreCase(f[0])) {
								expires = f[1];
							}
							else if ("domain".equalsIgnoreCase(f[0])) {
								domain = f[1];
							}
							else if ("path".equalsIgnoreCase(f[0])) {
								path = f[1];
							}
						}
						
					}
					
					System.out.println("cookieValue:" + cookieValue);
					System.out.println("expires:" + expires);
					System.out.println("path:" + path);
					System.out.println("domain:" + domain);
					System.out.println("secure:" + secure);
					 
					System.out.println("*****************************************");
			
   
				 }
				 
			 }
			
		}
		
	}

}

Output:

Cookie Found...
cookieValue:NID=52=PwcXVmIE4acIM9BYOwXfjcjbl3K5eKBlmY2jx_-oIWY9ZPCQr0WsDNCjCc4kqmCLysK6qUn1DlVhpQCSpoQoSskvRdAV4fptSuc2esPhqMLC9yb9QCTQWBFgayL8YdeK
expires:Sun, 29-Apr-2012 19:50:17 GMT
path:/
domain:.google.gr
secure:false
*****************************************
Cookie Found...
cookieValue:PREF=ID=da4bc4ff59cbdda5:FF=0:TM=1319917817:LM=1319917817:S=857qQm4Nt5qON_en
expires:Mon, 28-Oct-2013 19:50:17 GMT
path:/
domain:.google.gr
secure:false
*****************************************

This was an example of how to get cookies from HTTP connection in Java.

Byron Kiourtzoglou

Byron is a master software engineer working in the IT and Telecom domains. He is an applications developer in a wide variety of applications/services. He is currently acting as the team leader and technical architect for a proprietary service creation and integration platform for both the IT and Telecom industries in addition to a in-house big data real-time analytics solution. He is always fascinated by SOA, middleware services and mobile development. Byron is co-founder and Executive Editor at Java Code Geeks.
Subscribe
Notify of
guest

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

2 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Faizan Sayyed
6 years ago

thanks for the code..but how to implement this is android?

mufas
mufas
4 years ago

How to get JSESSION ID from headers ?

Back to top button