Java/JDK 6/Cookie
Fetch Cookie with CookieHandler, CookieManager and CookieStore
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 FetchCookie {
public static void main(String args[]) throws Exception {
String urlString = "http://java.sun.ru";
CookieManager manager = new CookieManager();
CookieHandler.setDefault(manager);
URL url = new URL(urlString);
URLConnection connection = url.openConnection();
Object obj = connection.getContent();
url = new URL(urlString);
connection = url.openConnection();
obj = connection.getContent();
CookieStore cookieJar = manager.getCookieStore();
List<HttpCookie> cookies = cookieJar.getCookies();
for (HttpCookie cookie : cookies) {
System.out.println(cookie);
}
}
}
Using CookieHandler in Java 5
#Code referenced from
#Chapter 6 - Extensible Markup Language (XML)
#Java 6 Platform Revealed
#by John Zukowski
#ISBN: 1590596609
#http://www.apress.ru/book/bookDisplay.html?bID=10109
import java.io.IOException;
import java.net.CookieHandler;
import java.net.URI;
import java.net.URL;
import java.net.URLConnection;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
public class Fetch5 {
public static void main(String args[]) throws Exception {
String urlString = "java.sun.ru";
CookieHandler.setDefault(new ListCookieHandler());
URL url = new URL(urlString);
URLConnection connection = url.openConnection();
Object obj = connection.getContent();
url = new URL(urlString);
connection = url.openConnection();
obj = connection.getContent();
}
}
class ListCookieHandler extends CookieHandler {
private List<Cookie> cookieJar = new LinkedList<Cookie>();
public void put(URI uri, Map<String, List<String>> responseHeaders) throws IOException {
List<String> setCookieList = responseHeaders.get("Set-Cookie");
if (setCookieList != null) {
for (String item : setCookieList) {
Cookie cookie = new Cookie(uri, item);
for (Cookie existingCookie : cookieJar) {
if ((cookie.getURI().equals(existingCookie.getURI()))
&& (cookie.getName().equals(existingCookie.getName()))) {
cookieJar.remove(existingCookie);
break;
}
}
cookieJar.add(cookie);
}
}
}
public Map<String, List<String>> get(URI uri, Map<String, List<String>> requestHeaders)
throws IOException {
StringBuilder cookies = new StringBuilder();
for (Cookie cookie : cookieJar) {
// Remove cookies that have expired
if (cookie.hasExpired()) {
cookieJar.remove(cookie);
} else if (cookie.matches(uri)) {
if (cookies.length() > 0) {
cookies.append(", ");
}
cookies.append(cookie.toString());
}
}
Map<String, List<String>> cookieMap = new HashMap<String, List<String>>(requestHeaders);
if (cookies.length() > 0) {
List<String> list = Collections.singletonList(cookies.toString());
cookieMap.put("Cookie", list);
}
System.out.println("CookieMap: " + cookieMap);
return Collections.unmodifiableMap(cookieMap);
}
}
class Cookie {
String name;
String value;
URI uri;
String domain;
Date expires;
String path;
private static DateFormat expiresFormat1 = new SimpleDateFormat("E, dd MMM yyyy k:m:s "GMT"",
Locale.US);
private static DateFormat expiresFormat2 = new SimpleDateFormat("E, dd-MMM-yyyy k:m:s "GMT"",
Locale.US);
public Cookie(URI uri, String header) {
String attributes[] = header.split(";");
String nameValue = attributes[0].trim();
this.uri = uri;
this.name = nameValue.substring(0, nameValue.indexOf("="));
this.value = nameValue.substring(nameValue.indexOf("=") + 1);
this.path = "/";
this.domain = uri.getHost();
for (int i = 1; i < attributes.length; i++) {
nameValue = attributes[i].trim();
int equals = nameValue.indexOf("=");
if (equals == -1) {
continue;
}
String name = nameValue.substring(0, equals);
String value = nameValue.substring(equals + 1);
if (name.equalsIgnoreCase("domain")) {
String uriDomain = uri.getHost();
if (uriDomain.equals(value)) {
this.domain = value;
} else {
if (!value.startsWith(".")) {
value = "." + value;
}
uriDomain = uriDomain.substring(uriDomain.indexOf("."));
if (!uriDomain.equals(value)) {
throw new IllegalArgumentException("Trying to set foreign cookie");
}
this.domain = value;
}
} else if (name.equalsIgnoreCase("path")) {
this.path = value;
} else if (name.equalsIgnoreCase("expires")) {
try {
this.expires = expiresFormat1.parse(value);
} catch (ParseException e) {
try {
this.expires = expiresFormat2.parse(value);
} catch (ParseException e2) {
throw new IllegalArgumentException("Bad date format in header: " + value);
}
}
}
}
}
public boolean hasExpired() {
if (expires == null) {
return false;
}
Date now = new Date();
return now.after(expires);
}
public String getName() {
return name;
}
public URI getURI() {
return uri;
}
public boolean matches(URI uri) {
if (hasExpired()) {
return false;
}
String path = uri.getPath();
if (path == null) {
path = "/";
}
return path.startsWith(this.path);
}
public String toString() {
StringBuilder result = new StringBuilder(name);
result.append("=");
result.append(value);
return result.toString();
}
}
Using CookieStore
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.CookieHandler;
import java.net.CookieManager;
import java.net.CookiePolicy;
import java.net.CookieStore;
import java.net.HttpCookie;
import java.net.URI;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
public class WebClient {
public static void main(String[] args) throws Exception {
CookieStore store = new MyCookieStore();
CookiePolicy policy = new MyCookiePolicy();
CookieManager handler = new CookieManager(store, policy);
CookieHandler.setDefault(handler);
URL url = new URL("http://localhost:8080/cookieTest.jsp");
URLConnection conn = url.openConnection();
InputStream in = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String input;
while ((input = reader.readLine()) != null) {
System.out.println(input);
}
reader.close();
}
}
class MyCookiePolicy implements CookiePolicy {
public boolean shouldAccept(URI uri, HttpCookie cookie) {
// String host = uri.getHost();
// return host.equals("localhost");
return true;
}
}
class MyCookieStore implements CookieStore {
private Map<URI, List<HttpCookie>> map = new HashMap<URI, List<HttpCookie>>();
public void add(URI uri, HttpCookie cookie) {
List<HttpCookie> cookies = map.get(uri);
if (cookies == null) {
cookies = new ArrayList<HttpCookie>();
map.put(uri, cookies);
}
cookies.add(cookie);
}
public List<HttpCookie> get(URI uri) {
List<HttpCookie> cookies = map.get(uri);
if (cookies == null) {
cookies = new ArrayList<HttpCookie>();
map.put(uri, cookies);
}
return cookies;
}
public List<HttpCookie> getCookies() {
Collection<List<HttpCookie>> values = map.values();
List<HttpCookie> result = new ArrayList<HttpCookie>();
for (List<HttpCookie> value : values) {
result.addAll(value);
}
return result;
}
public List<URI> getURIs() {
Set<URI> keys = map.keySet();
return new ArrayList<URI>(keys);
}
public boolean remove(URI uri, HttpCookie cookie) {
List<HttpCookie> cookies = map.get(uri);
if (cookies == null) {
return false;
}
return cookies.remove(cookie);
}
public boolean removeAll() {
map.clear();
return true;
}
}
The cookieTest.jsp page
<%
Cookie cookie = new Cookie ("username", "guest");
cookie.setMaxAge (100);
response.addCookie (cookie);
%>
<html>
<head>
<title>HttpCookie Demo</title>
</head>
<body>
Add cookie. Cookie name = <%=cookie.getName () +". Cookie value = " + cookie.getValue () %>
</body>
</html>
//Reference:
//Java 6 New Features: A Tutorial
//by Budi Kurniawan
//Brainy Software Corp. 2006
//Chapter 4 - Networking
//# ISBN-10: 0975212885
//# ISBN-13: 978-0975212882