HttpURLConnection 中Cookie 使用
如果想通過 HttpURLConnection 訪問網(wǎng)站,網(wǎng)站返回cookie信息,下次再通過HttpURLConnection訪問時(shí),把網(wǎng)站返回 cookie信息再返回給該網(wǎng)站。可以使用下面代碼。
CookieManager manager = new CookieManager(); CookieHandler.setDefault(manager);通過這兩行代碼就可以把網(wǎng)站返回的cookie信息存儲(chǔ)起來,下次訪問網(wǎng)站的時(shí)候,自動(dòng)幫你把cookie信息帶上。
CookieManager還可以設(shè)置CookiePolicy。設(shè)置如下:
CookieManager manager = new CookieManager(); //設(shè)置cookie策略,只接受與你對(duì)話服務(wù)器的cookie,而不接收Internet上其它服務(wù)器發(fā)送的cookie manager.setCookiePolicy(CookiePolicy.ACCEPT_ORIGINAL_SERVER);有關(guān)CookiePolicy請(qǐng)?jiān)斂?#xff1a; CookiePolicy 原理解析
CookieHandler 源碼分析
public abstract class CookieHandler {private static CookieHandler cookieHandler;public synchronized static CookieHandler getDefault() {SecurityManager sm = System.getSecurityManager();if (sm != null) {sm.checkPermission(SecurityConstants.GET_COOKIEHANDLER_PERMISSION);}return cookieHandler;}public synchronized static void setDefault(CookieHandler cHandler) {SecurityManager sm = System.getSecurityManager();if (sm != null) {sm.checkPermission(SecurityConstants.SET_COOKIEHANDLER_PERMISSION);}cookieHandler = cHandler;}public abstract Map<String, List<String>>get(URI uri, Map<String, List<String>> requestHeaders)throws IOException;public abstract voidput(URI uri, Map<String, List<String>> responseHeaders)throws IOException; }CookieHandler是抽象類,內(nèi)部提供了靜態(tài)的setDefault方法。
并且 private static CookieHandler cookieHandler; 是靜態(tài)的。
子類需要實(shí)現(xiàn)get()和put()方法。
get()方法返回該uri相關(guān)的cookie。
put()方法是存儲(chǔ)該uri相關(guān)的cookie。
jdk1.6中提供了CookieHandler的實(shí)現(xiàn)類CookieManager。
CookieManager 源碼分析
get()方法
CookieManager.get() 方法實(shí)現(xiàn)了從CookieStore中獲取該uri對(duì)應(yīng)的cookie。
put() 方法
首先解析http 相應(yīng)頭信息中的cookie,并存儲(chǔ)到 List cookies 中。
循環(huán)cookies中的cookie,根據(jù)設(shè)置的CookiePolicy來判斷是否接收該Cookie信息,
如果接收則存儲(chǔ)到CookieStore。
Cookie實(shí)現(xiàn)機(jī)制
這樣每次在調(diào)用HttpURLConnection訪問網(wǎng)站的時(shí)候,通過CookieHandler.getDefault()方法獲取CookieManager實(shí)例(靜態(tài)的方法,全局都可用)。
從解析http的響應(yīng)頭中的cookie調(diào)用CookieHandler中的put方法存放到CookieStore中。
再次訪問網(wǎng)站的時(shí)候調(diào)用CookieHandler中的get方法獲取該uri響應(yīng)的cookie,并提交到該站點(diǎn)中。
這樣開發(fā)人員就不需要干預(yù)cookie信息,則每次訪問網(wǎng)站會(huì)自動(dòng)攜帶cookie。
代碼示例
本例子中使用到了CookieHandler、CookieManager 、CookieStore、 HttpCookie。
public class CookieManagerDemo {//打印cookie信息public static void printCookie(CookieStore cookieStore){List<HttpCookie> listCookie = cookieStore.getCookies();listCookie.forEach(httpCookie -> {System.out.println("--------------------------------------");System.out.println("class : "+httpCookie.getClass());System.out.println("comment : "+httpCookie.getComment());System.out.println("commentURL : "+httpCookie.getCommentURL());System.out.println("discard : "+httpCookie.getDiscard());System.out.println("domain : "+httpCookie.getDomain());System.out.println("maxAge : "+httpCookie.getMaxAge());System.out.println("name : "+httpCookie.getName());System.out.println("path : "+httpCookie.getPath());System.out.println("portlist : "+httpCookie.getPortlist());System.out.println("secure : "+httpCookie.getSecure());System.out.println("value : "+httpCookie.getValue());System.out.println("version : "+httpCookie.getVersion());System.out.println("httpCookie : "+httpCookie);});}public static void requestURL() throws Exception{URL url = new URL("http://192.168.3.249:9000/webDemo/index.jsp");HttpURLConnection conn = (HttpURLConnection)url.openConnection();String basic = Base64.getEncoder().encodeToString("infcn:123456".getBytes());conn.setRequestProperty("Proxy-authorization", "Basic " + basic);BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));String line = null;while((line=br.readLine())!=null){System.out.println(line);}br.close();}public static void main(String[] args) throws Exception {CookieManager manager = new CookieManager();//設(shè)置cookie策略,只接受與你對(duì)話服務(wù)器的cookie,而不接收Internet上其它服務(wù)器發(fā)送的cookiemanager.setCookiePolicy(CookiePolicy.ACCEPT_ORIGINAL_SERVER);CookieHandler.setDefault(manager);printCookie(manager.getCookieStore());//第一次請(qǐng)求requestURL();printCookie(manager.getCookieStore());//第二次請(qǐng)求requestURL();}}從抓包結(jié)果中發(fā)現(xiàn),第二次訪問該站點(diǎn)的時(shí)候,會(huì)自動(dòng)攜帶Cookie信息。
本人簡(jiǎn)書blog地址:http://www.jianshu.com/u/1f0067e24ff8????
點(diǎn)擊這里快速進(jìn)入簡(jiǎn)書
GIT地址:http://git.oschina.net/brucekankan/
點(diǎn)擊這里快速進(jìn)入GIT
總結(jié)
以上是生活随笔為你收集整理的HttpURLConnection 中Cookie 使用的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: CookiePolicy 原理解析
- 下一篇: java.net.Socket 解析