国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學院 > 開發設計 > 正文

JavaSe:Cookie管理的API介紹

2019-11-14 15:36:22
字體:
來源:轉載
供稿:網友

CookieManager

 在使用HttpURLConnection中,并沒有關于Cookie的管理。如果使用java程序時,怎么管理cookie呢?

 Cookie案例

 

1. User Agent -> ServerPOST /acme/login HTTP/1.1[form data]2. Server -> User AgentHTTP/1.1 200 OKSet-Cookie2: Customer="WILE_E_COYOTE"; Version="1"; Path="/acme"3. User Agent -> ServerPOST /acme/pickitem HTTP/1.1Cookie: $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;elsecookieValue = cookieValue + ";" + v;} 

 

 

CookieHandler

這兩個方法是常見的方法,其實還有另外的專門管理Cookie的處理:CookieHandler。

 

public abstract Map<String,List<String>> get(URI uri,Map<String,List<String>> requestHeaders)throws IOExceptionGets 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)過程。

 


發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 巴彦淖尔市| 襄樊市| 读书| 兴和县| 芷江| 双流县| 涞源县| 清丰县| 辉县市| 台州市| 土默特右旗| 额敏县| 贡嘎县| 汝南县| 海淀区| 苍溪县| 绥滨县| 南江县| 曲松县| 镇坪县| 峡江县| 三门峡市| 凌云县| 收藏| 鄢陵县| 井陉县| 沙坪坝区| 德安县| 九江市| 杂多县| 平塘县| 信阳市| 绥德县| 枣强县| 龙川县| 拉萨市| 镇巴县| 郓城县| 诸暨市| 闻喜县| 嫩江县|