Cookies
The java.net package includes classes and interfaces that help manage cookies and can be used to create a stateful HTTP session.
The classes are CookieHandler, CookieManager, and HttpCookie. The interfaces are CookiePolicy and CookieStore.
The following code lists all cookies for a specific domain.
import java.io.IOException;
import java.net.CookieHandler;
import java.net.CookieManager;
import java.net.CookiePolicy;
import java.net.HttpCookie;
import java.net.URL;
import java.util.List;
public class Main{
public static void main(String[] args) throws IOException {
CookieManager cm = new CookieManager();
cm.setCookiePolicy(CookiePolicy.ACCEPT_ALL);
CookieHandler.setDefault(cm);
new URL("http://google.com").openConnection().getContent();
List<HttpCookie> cookies = cm.getCookieStore().getCookies();
for (HttpCookie cookie : cookies) {
System.out.println("Name = " + cookie.getName());
System.out.println("Value = " + cookie.getValue());
System.out.println("Lifetime (seconds) = " + cookie.getMaxAge());
System.out.println("Path = " + cookie.getPath());
System.out.println();
}
}
}