JavaSe:Cookie 管理的API介绍

CookieManager

 在使用HttpURLConnection中,并没有关于Cookie的管理。如果使用Java程序时,怎么管理cookie呢?

 Cookie案例

1. User Agent -> Server
POST /acme/login HTTP/1.1
[form data]
2. Server -> User Agent
HTTP/1.1 200 OK
Set-Cookie2: Customer="WILE_E_COYOTE"; Version="1"; Path="/acme"
3. User Agent -> Server
POST /acme/pickitem HTTP/1.1
Cookie: $Version="1"; Customer="WILE_E_COYOTE"; $Path="/acme"
[form data]

Cookie的两种形式

会话 Cookie

在使用applet、application时, Session Cookie被存储在内存中,当程序退出时,cookie会被自动的删除。Cookie中会保存session的id,这样在同一个站点的不同页面之间切换时,就不需要再重复登录。

持久化Cookie

与Session Cookie不同的是,在应用程序退出时,cookie不会被删除,直到它过期时,都会被删除。

  

编程方式访问Cookie

请求发送前设置Cookie

发送HTTP请求时,可以使用URLConnection.setRequestProperty(String key, String value)方式设置Cookie。

URL url = new URL( "http://java.sun.com/" );
URLConnection conn = url.openConnection(); 
conn.setRequestProperty("Cookie", "foo=bar"); 
InputStream is = conn.getInputStream(); 
......


接收到响应后查看
Cookie 

    接收到响应后,可以使用URLConnection.getHeaderFields()方式来查看Cookie:

URL url = new URL( "http://java.sun.com/" ); 
URLConnection conn = url.openConnection(); 
conn.connect(); 
..... 
Map<String, List<String>> headers = conn.getHeaderFields(); 
List<String> values = headers.get("Set-Cookie"); 

String cookieValue = null; 
for (Iterator iter = values.iterator(); iter.hasNext(); ) {
String v = values.next(); 
if (cookieValue == null)
cookieValue = v;
else
cookieValue = cookieValue + ";" + v;
} 

CookieHandler

这两个方法是常见的方法,其实还有另外的专门管理Cookie的处理:CookieHandler。

public abstract Map<String,List<String>> get(URI uri,Map<String,List<String>> requestHeaders)
throws IOException
Gets all the applicable cookies from a cookie cache for the specified uri in the request header. HTTP protocol implementers should make sure that this method is called after all request headers related to choosing cookies are added, and before the request is sent. 
该方法用于从Cookie Cache(也就是CookieStore)中获取所有的可以使用的Cookie。
HTTP协议的实现应该确保这个方法在相关Cookie 请求头被设置后,在请求发送之前被调用。

  从方法的说明上来看, 这个是回调函数,这个方法会在HTTPURLConnection.setRequestProperty(“Cookie”,”xxxx=yyy”)执行后,在HttpURLConnection.connect()之前被自动调用,不需要我们在代码里进行调用。

该方法的返回值是一个Map,返回值中的数据将作为请求头的一部分发送到服务器。对应于案例中的(3)过程。

  与此对应的,put方法是将响应头中的Cookie设置到客户端的Cookie Cache中。

默认的服务端返回的响应头中是使用set-cookie作为要设置Cookie的标识的。

客户端(例如浏览器)接收到响应后,使用put()将要set-cache中的数据设置到客户端的Cookie Cache中。对应于案例中的(2)过程。

原文地址:https://www.cnblogs.com/f1194361820/p/4820895.html