使用HttpURLConnection發送post和get請求緩存
但咱們經常會碰到這樣一種狀況:服務器
經過HttpURLConnection來模擬模擬用戶登陸Web服務器,服務器使用cookie進行用戶認證。在模擬登陸時,Post表單數據後能夠正確登陸(登錄成功時會response一個cookie,而後redirect到main page,不成功則redirect到login page),可是在使用HttpURLConnection再次鏈接服務器其餘頁面(或者即便是當前的response裏是redirect的page)時,服務器都會認爲是全新的一個Session。cookie
解決方法有2步:session
1. 調用HttpURLConnection (send post request to login page)的setInstanceFollowRedirects()方法,參數爲false (這樣不會去獲取redirect page)app
2. 獲取HttpURLConnection send post request to login page的session id,而後在以後每一次的connection裏都加上該session id函數
public static String sessionId = ""; public static void sendLoginRequest() throws IOException { URL loginUrl = new URL("http://xxx"); HttpURLConnection connection = (HttpURLConnection) loginUrl.openConnection(); // Output to the connection. Default is // false, set to true because post // method must write something to the // connection // 設置是否向connection輸出,由於這個是post請求,參數要放在 // http正文內,所以須要設爲true connection.setDoOutput(true); // Read from the connection. Default is true. connection.setDoInput(true); // Set the post method. Default is GET connection.setRequestMethod("POST"); // Post cannot use caches // Post 請求不能使用緩存 connection.setUseCaches(false); // This method takes effects to // every instances of this class. // URLConnection.setFollowRedirects是static函數,做用於全部的URLConnection對象。 // connection.setFollowRedirects(true); // This methods only // takes effacts to this // instance. // URLConnection.setInstanceFollowRedirects是成員函數,僅做用於當前函數 connection.setInstanceFollowRedirects(false); // Set the content type to urlencoded, // because we will write // some URL-encoded content to the // connection. Settings above must be set before connect! // 配置本次鏈接的Content-type,配置爲application/x-www-form-urlencoded的 // 意思是正文是urlencoded編碼過的form參數,下面咱們能夠看到咱們對正文內容使用URLEncoder.encode // 進行編碼 connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); // 鏈接,從postUrl.openConnection()至此的配置必需要在connect以前完成, // 要注意的是connection.getOutputStream會隱含的進行connect。 connection.connect(); DataOutputStream out = new DataOutputStream(connection .getOutputStream()); // 要傳的參數 String content = URLEncoder.encode("username", "UTF-8") + "=" + URLEncoder.encode("XXX", "UTF-8"); content += "&" + URLEncoder.encode("password", "UTF-8") + "=" + URLEncoder.encode("XXXX", "UTF-8"); // DataOutputStream.writeBytes將字符串中的16位的unicode字符以8位的字符形式寫道流裏面 out.writeBytes(content); out.flush(); out.close(); // flush and close //Get Session ID String key = ""; if (connection != null) { for (int i = 1; (key = connection.getHeaderFieldKey(i)) != null; i++) { if (key.equalsIgnoreCase("set-cookie")) { sessionId = connection.getHeaderField(key); sessionId = sessionId.substring(0, sessionId.indexOf(";")); } } } connection.disconnect(); }
而後以後每一次connection都要加上這個session id:post