How to Get Cookies in Java


In this example we will show how to get the Cookies in Java.

Source Code

package com.beginner.examples;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.*;
import java.util.List;
import java.util.Map;

import javax.servlet.http.*;

public class GetCookiesExample {

    public static void main(String[] args){
    	try
    	{
    		CookieManager m=new CookieManager();
    		m.setCookiePolicy(CookiePolicy.ACCEPT_ORIGINAL_SERVER);
    		CookieHandler.setDefault(m);
    		URL	url=new URL("https://www.baidu.com/");
    		HttpURLConnection connect= (HttpURLConnection) url.openConnection();
    		Map<String, List> httpResponseHeaders = connect.getHeaderFields();
    		List cookies = m.getCookieStore().getCookies();
    		for (HttpCookie cookie: cookies) 
    		{
	    		System.out.println(cookie.getName() + " : " + cookie.getValue());
    		}
    	}
    	catch (Exception e)
    	{
    		e.printStackTrace();
    	}
    }
    
}

Output:

BDORZ : 27315

References

Imported packages in Java documentation:

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments