CookieManager
在使用HttpURLConnection中,并沒有關于Cookie的管理。如果使用java程序時,怎么管理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
在使用applet、application時, session Cookie被存儲在內存中,當程序退出時,cookie會被自動的刪除。Cookie中會保存session的id,這樣在同一個站點的不同頁面之間切換時,就不需要再重復登錄。
持久化Cookie
與Session 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;}
這兩個方法是常見的方法,其實還有另外的專門管理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)過程。
新聞熱點
疑難解答