JavaSe:Cookie管理的API介绍

王朝学院·作者佚名  2016-08-27
窄屏简体版  字體: 小  |  中  |  大  |  超大  

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 200OK

Set-Cookie2: Customer="WILE_E_COYOTE"; Version="1"; Path="/acme"

3. User Agent ->Server

POST/acme/pickitem HTTP/1.1Cookie: $Version="1"; Customer="WILE_E_COYOTE"; $Path="/acme"[form data]

Cookie的两种形式会话Cookie

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

持久化Cookie

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

编程方式访问Cookie请求发送前设置Cookie

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

URL url =newURL( "http://java.sun.com/");

URLConnection conn=url.openConnection();

conn.setRequestProperty("Cookie", "foo=bar");

InputStream is=conn.getInputStream();

......

接收到响应后查看Cookie

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

URL url =newURL( "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;elsecookieValue= cookieValue + ";" +v;

}

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

publicabstractMap<String,List<String>> get(URI uri,Map<String,List<String>>requestHeaders)throwsIOException

Gets all the applicable cookies from a cookie cacheforthe specified uri in the request header. HTTP protocol implementers should make sure thatthismethod 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)过程。

 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
© 2005- 王朝網路 版權所有 導航