使用HttpURLConnection發送post和get請求
1、http://blog.csdn.net/pandazxx/archive/2007/06/18/1657109.aspx
2、http://blog.csdn.net/pandazxx/archive/2007/06/20/1660008.aspx
但我們常常會碰到這樣一種情況:
通過HttpURLConnection來類比類比使用者登入Web伺服器,伺服器使用cookie進行使用者認證。在類比登入時,Post表單資料後可以正確登入(登陸成功時會response一個cookie,然後redirect到main page,不成功則redirect到login page),但是在使用HttpURLConnection再次串連伺服器其他頁面(或者即使是當前的response裡是redirect的page)時,伺服器都會認為是全新的一個Session。
解決方案有2步:
1. 調用HttpURLConnection (send post request to login page)的setInstanceFollowRedirects()方法,參數為false (這樣不會去擷取redirect page)
2. 擷取HttpURLConnection send post request to login page的session id,然後在之後每一次的connection裡都加上該session id
Example:
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:
URL url = new URL("http:......");HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.setRequestProperty("Cookie",this.sessionId);connection.connect();