从http连接获取Cookies
/** 来自 n o w j a v a . c o m**/ import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.util.Iterator; import java.util.List; import java.util.Map; public class GetCookiesFromThttpConnection { public static void main(String[] args) { try { URL url = new URL("http://www.google.com"); java.net.URLConnection conn = url.openConnection(); Map<String, List<String>> headers = conn.getHeaderFields(); Iterator<String> iter = headers.keySet().iterator(); while (iter.hasNext()) { String key = iter.next(); if ("Set-Cookie".equalsIgnoreCase(key)) {/*N o w J a v a . c o m*/ List<String> values = headers.get(key); for (String value : values) { System.out.println("found ...:" + value); String[] fields = value.split(";\\s*"); String cookiValue = fields[0]; String expries = null; String path = null; String domain = null; boolean secure = false; for (int i = 0; i < fields.length; i++) { if ("secure".equalsIgnoreCase(fields[i])) { secure = true; } else if (fields[i].indexOf('=') > 0) { String[] f = fields[i].split("="); if ("expires".equalsIgnoreCase(f[0])) { expries = f[1]; } else if ("domain".equalsIgnoreCase(f[0])) { domain = f[1]; } else if ("path".equalsIgnoreCase(f[0])) { path = f[1]; } } } System.out.println("cookiValue :" + cookiValue); System.out.println("expries :" + expries); System.out.println("path :" + path); System.out.println("domain :" + domain);