Example of HttpCookie in Java
April 06, 2013
HttpCookie belongs to the package java.net and is available since jdk1.6. HttpCookie represents the cookie which provides the stateful session. HttpCookie is obtained from CookieStore. HttpCookie provides complete information about the cookie like max age, domain name, value path etc. Find below the sample usage of HttpCookie.
HttpCookieTest.java
package com.concretepage; import java.net.CookieHandler; import java.net.CookieManager; import java.net.CookieStore; import java.net.HttpCookie; import java.net.URL; import java.net.URLConnection; import java.util.List; public class HttpCookieTest { public static void main(String args[]) throws Exception { String urlString = "https://www.facebook.com"; CookieManager ckman = new CookieManager(); CookieHandler.setDefault(ckman); URL url = new URL(urlString); URLConnection connection = url.openConnection(); connection.getContent(); CookieStore ckStore = ckman.getCookieStore(); List<HttpCookie> cks = ckStore.getCookies(); //iterate HttpCookie object for (HttpCookie ck : cks) { System.out.println("--- Cookie Information ---"); //gets domain set for the cookie System.out.println(ck.getDomain()); //gets max age of the cookie System.out.println(ck.getMaxAge()); // gets name cookie System.out.println(ck.getName()); //gets path of the server System.out.println(ck.getPath()); //gets boolean if cookie is being sent with secure protocol System.out.println(ck.getSecure()); //gets the value of the cookie System.out.println(ck.getValue()); //gets the version of the protocol with which the given cookie is related. System.out.println(ck.getVersion()); } } }
--- Cookie Information --- .facebook.com 7775997 fr / false 0m7X4Insdyp2ohS11..BXqstJ.bK.AAA.0.0.BXqstJ.AWWglgdb 0