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> map = new HashMap>();
public void add(URI uri, HttpCookie cookie) {
List cookies = map.get(uri);
if (cookies == null) {
cookies = new ArrayList();
map.put(uri, cookies);
}
cookies.add(cookie);
}
public List get(URI uri) {
List cookies = map.get(uri);
if (cookies == null) {
cookies = new ArrayList();
map.put(uri, cookies);
}
return cookies;
}
public List getCookies() {
Collection> values = map.values();
List result = new ArrayList();
for (List value : values) {
result.addAll(value);
}
return result;
}
public List getURIs() {
Set keys = map.keySet();
return new ArrayList(keys);
}
public boolean remove(URI uri, HttpCookie cookie) {
List 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);
%>
HttpCookie Demo
Add cookie. Cookie name = <%=cookie.getName () +". Cookie value = " + cookie.getValue () %>
//Reference:
//Java 6 New Features: A Tutorial
//by Budi Kurniawan
//Brainy Software Corp. 2006
//Chapter 4 - Networking
//# ISBN-10: 0975212885
//# ISBN-13: 978-0975212882