使用HttpURLConnection發送post和get請求

來源:互聯網
上載者:User

使用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(); 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.