Android網路編程之Http通訊

來源:互聯網
上載者:User
標籤:Android Http 網路編程 url 移動開發 允許轉載,轉載時請務必以超連結形式標明文章 原始出處 、作者資訊和本聲明。否則將追究法律責任。http://52android.blog.51cto.com/2554429/496621Android中提供的HttpURLConnection和HttpClient介面可以用來開發HTTP程式。以下是本人在學習中的總結與歸納。
1. HttpURLConnection介面
    首先需要明確的是,Http通訊中的POST和GET請求方式的不同。GET可以獲得靜態頁面,也可以把參數放在URL字串後面,傳遞給伺服器。而POST方法的參數是放在Http請求中。因此,在編程之前,應當首先明確使用的要求方法,然後再根據所使用的方式選擇相應的編程方式。
    HttpURLConnection是繼承於URLConnection類,二者都是抽象類別。其對象主要通過URL的openConnection方法獲得。建立方法如下代碼所示:

 
 

     
  1. URL url = new URL("http://www.51cto.com/index.jsp?par=123456");  
  2. HttpURLConnection urlConn=(HttpURLConnection)url.openConnection(); 

   

    通過以下方法可以對請求的屬性進行一些設定,如下所示:

 
 

     
  1. //設定輸入和輸出資料流  
  2. urlConn.setDoOutput(true);  
  3. urlConn.setDoInput(true);  
  4. //佈建要求方式為POST  
  5. urlConn.setRequestMethod("POST");  
  6. //POST請求不能使用緩衝  
  7. urlConn.setUseCaches(false);  
  8. //關閉串連  
  9. urlConn.disConnection();  
  10.  

HttpURLConnection預設使用GET方式,例如下面代碼所示:

 
 

     
  1. //使用HttpURLConnection開啟串連  
  2.                 HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();  
  3.                 //得到讀取的內容(流)  
  4.                 InputStreamReader in = new InputStreamReader(urlConn.getInputStream());  
  5.                 // 為輸出建立BufferedReader  
  6.                 BufferedReader buffer = new BufferedReader(in);  
  7.                 String inputLine = null;  
  8.                 //使用迴圈來讀取獲得的資料  
  9.                 while (((inputLine = buffer.readLine()) != null))  
  10.                 {  
  11.                     //我們在每一行後面加上一個"\n"來換行  
  12.                     resultData += inputLine + "\n";  
  13.                 }           
  14.                 //關閉InputStreamReader  
  15.                 in.close();  
  16.                 //關閉http串連  
  17.                 urlConn.disconnect(); 

    如果需要使用POST方式,則需要setRequestMethod設定。代碼如下:

 
 

     
  1. String httpUrl = "http://192.168.1.110:8080/httpget.jsp";  
  2.         //獲得的資料  
  3.         String resultData = "";  
  4.         URL url = null;  
  5.         try 
  6.         {  
  7.             //構造一個URL對象  
  8.             url = new URL(httpUrl);   
  9.         }  
  10.         catch (MalformedURLException e)  
  11.         {  
  12.             Log.e(DEBUG_TAG, "MalformedURLException");  
  13.         }  
  14.         if (url != null)  
  15.         {  
  16.             try 
  17.             {  
  18.                 // 使用HttpURLConnection開啟串連  
  19.                 HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();  
  20.                 //因為這個是post請求,設立需要設定為true  
  21.                 urlConn.setDoOutput(true);  
  22.                 urlConn.setDoInput(true);  
  23.                 // 設定以POST方式  
  24.                 urlConn.setRequestMethod("POST");  
  25.                 // Post 請求不能使用緩衝  
  26.                 urlConn.setUseCaches(false);  
  27.                 urlConn.setInstanceFollowRedirects(true);  
  28.                 // 配置本次串連的Content-type,配置為application/x-www-form-urlencoded的  
  29.                 urlConn.setRequestProperty("Content-Type","application/x-www-form-urlencoded");  
  30.                 // 串連,從postUrl.openConnection()至此的配置必須要在connect之前完成,  
  31.                 // 要注意的是connection.getOutputStream會隱含的進行connect。  
  32.                 urlConn.connect();  
  33.                 //DataOutputStream流  
  34.                 DataOutputStream out = new DataOutputStream(urlConn.getOutputStream());  
  35.                 //要上傳的參數  
  36.                 String content = "par=" + URLEncoder.encode("ABCDEFG", "gb2312");  
  37.                 //將要上傳的內容寫入流中  
  38.                 out.writeBytes(content);   
  39.                 //重新整理、關閉  
  40.                 out.flush();  
  41.                 out.close();  

2. HttpClient介面
    使用Apache提供的HttpClient介面同樣可以進行HTTP操作。
    對於GET和POST要求方法的操作有所不同。GET方法的作業碼樣本如下:

 
 

     
  1. // http地址  
  2.         String httpUrl = "http://192.168.1.110:8080/httpget.jsp?par=HttpClient_android_Get";  
  3.         //HttpGet連線物件  
  4.         HttpGet httpRequest = new HttpGet(httpUrl);  
  5.          //取得HttpClient對象  
  6.             HttpClient httpclient = new DefaultHttpClient();  
  7.             //請求HttpClient,取得HttpResponse  
  8.             HttpResponse httpResponse = httpclient.execute(httpRequest);  
  9.             //請求成功  
  10.             if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK)  
  11.             {  
  12.                 //取得返回的字串  
  13.                 String strResult = EntityUtils.toString(httpResponse.getEntity());  
  14.                 mTextView.setText(strResult);  
  15.             }  
  16.             else 
  17.             {  
  18.                 mTextView.setText("請求錯誤!");  
  19.             }  
  20.         } 

    使用POST方法進行參數傳遞時,需要使用NameValuePair來儲存要傳遞的參數。,另外,還需要設定所使用的字元集。代碼如下所示:

 

 
 

     
  1. // http地址  
  2.         String httpUrl = "http://192.168.1.110:8080/httpget.jsp";  
  3.         //HttpPost連線物件  
  4.         HttpPost httpRequest = new HttpPost(httpUrl);  
  5.         //使用NameValuePair來儲存要傳遞的Post參數  
  6.         List<NameValuePair> params = new ArrayList<NameValuePair>();  
  7.         //添加要傳遞的參數  
  8.         params.add(new BasicNameValuePair("par", "HttpClient_android_Post"));  
  9.         //設定字元集  
  10.             HttpEntity httpentity = new UrlEncodedFormEntity(params, "gb2312");  
  11.             //請求httpRequest  
  12.             httpRequest.setEntity(httpentity);  
  13.             //取得預設的HttpClient  
  14.             HttpClient httpclient = new DefaultHttpClient();  
  15.             //取得HttpResponse  
  16.             HttpResponse httpResponse = httpclient.execute(httpRequest);  
  17.             //HttpStatus.SC_OK表示串連成功  
  18.             if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK)  
  19.             {  
  20.                 //取得返回的字串  
  21.                 String strResult = EntityUtils.toString(httpResponse.getEntity());  
  22.                 mTextView.setText(strResult);  
  23.             }  
  24.             else 
  25.             {  
  26.                 mTextView.setText("請求錯誤!");  
  27.             }  
  28.         } 

    HttpClient實際上是對Java提供方法的一些封裝,在HttpURLConnection中的輸入輸出資料流操作,在這個介面中被統一封裝成了HttpPost(HttpGet)和HttpResponse,這樣,就減少了操作的繁瑣性。

    另外,在使用POST方式進行傳輸時,需要進行字元編碼。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.