Android中的幾種網路請求方式詳解 .

來源:互聯網
上載者:User

 

Android應用經常會和伺服器端互動,這就需要手機用戶端發送網路請求,下面介紹四種常用網路請求方式,我這邊是通過Android單元測試來完成這四種方法的,還不清楚Android的單元測試的同學們請看Android開發技巧總結中的Android單元測試的步驟一文。

java.net包中的HttpURLConnection類

Get方式:

view plaincopy to clipboardprint?
  1. // Get方式請求   
  2. public static void requestByGet() throws Exception {  
  3.     String path = "https://reg.163.com/logins.jsp?id=helloworld&pwd=android";  
  4.     // 建立一個URL對象   
  5.     URL url = new URL(path);  
  6.     // 開啟一個HttpURLConnection串連   
  7.     HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();  
  8.     // 設定連線逾時時間   
  9.     urlConn.setConnectTimeout(5 * 1000);  
  10.     // 開始串連   
  11.     urlConn.connect();  
  12.     // 判斷請求是否成功   
  13.     if (urlConn.getResponseCode() == HTTP_200) {  
  14.         // 擷取返回的資料   
  15.         byte[] data = readStream(urlConn.getInputStream());  
  16.         Log.i(TAG_GET, "Get方式請求成功,返回資料如下:");  
  17.         Log.i(TAG_GET, new String(data, "UTF-8"));  
  18.     } else {  
  19.         Log.i(TAG_GET, "Get方式請求失敗");  
  20.     }  
  21.     // 關閉串連   
  22.     urlConn.disconnect();  
  23. }  

Post方式:

view plaincopy to clipboardprint?
  1. // Post方式請求   
  2. public static void requestByPost() throws Throwable {  
  3.     String path = "https://reg.163.com/logins.jsp";  
  4.     // 請求的參數轉換為byte數組   
  5.     String params = "id=" + URLEncoder.encode("helloworld", "UTF-8")  
  6.             + "&pwd=" + URLEncoder.encode("android", "UTF-8");  
  7.     byte[] postData = params.getBytes();  
  8.     // 建立一個URL對象   
  9.     URL url = new URL(path);  
  10.     // 開啟一個HttpURLConnection串連   
  11.     HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();  
  12.     // 設定連線逾時時間   
  13.     urlConn.setConnectTimeout(5 * 1000);  
  14.     // Post請求必須設定允許輸出   
  15.     urlConn.setDoOutput(true);  
  16.     // Post請求不能使用緩衝   
  17.     urlConn.setUseCaches(false);  
  18.     // 設定為Post請求   
  19.     urlConn.setRequestMethod("POST");  
  20.     urlConn.setInstanceFollowRedirects(true);  
  21.     // 配置請求Content-Type
      
  22.     urlConn.setRequestProperty("Content-Type",  
  23.             "application/x-www-form-urlencode");  
  24.     // 開始串連   
  25.     urlConn.connect();  
  26.     // 發送請求參數   
  27.     DataOutputStream dos = new DataOutputStream(urlConn.getOutputStream());  
  28.     dos.write(postData);  
  29.     dos.flush();  
  30.     dos.close();  
  31.     // 判斷請求是否成功   
  32.     if (urlConn.getResponseCode() == HTTP_200) {  
  33.         // 擷取返回的資料   
  34.         byte[] data = readStream(urlConn.getInputStream());  
  35.         Log.i(TAG_POST, "Post請求方式成功,返回資料如下:");  
  36.         Log.i(TAG_POST, new String(data, "UTF-8"));  
  37.     } else {  
  38.         Log.i(TAG_POST, "Post方式請求失敗");  
  39.     }  
  40. }  

  

org.apache.http包中的HttpGet和HttpPost類

Get方式:

view plaincopy to clipboardprint?
  1. // HttpGet方式請求   
  2. public static void requestByHttpGet() throws Exception {  
  3.     String path = "https://reg.163.com/logins.jsp?id=helloworld&pwd=android";  
  4.     // 建立HttpGet對象   
  5.     HttpGet httpGet = new HttpGet(path);  
  6.     // 擷取HttpClient對象   
  7.     HttpClient httpClient = new DefaultHttpClient();  
  8.     // 擷取HttpResponse執行個體   
  9.     HttpResponse httpResp = httpClient.execute(httpGet);  
  10.     // 判斷是夠請求成功   
  11.     if (httpResp.getStatusLine().getStatusCode() == HTTP_200) {  
  12.         // 擷取返回的資料   
  13.         String result = EntityUtils.toString(httpResp.getEntity(), "UTF-8");  
  14.         Log.i(TAG_HTTPGET, "HttpGet方式請求成功,返回資料如下:");  
  15.         Log.i(TAG_HTTPGET, result);  
  16.     } else {  
  17.         Log.i(TAG_HTTPGET, "HttpGet方式請求失敗");  
  18.     }  
  19. }  

Post方式:

view plaincopy to clipboardprint?
  1. // HttpPost方式請求   
  2. public static void requestByHttpPost() throws Exception {  
  3.     String path = "https://reg.163.com/logins.jsp";  
  4.     // 建立HttpPost對象   
  5.     HttpPost httpPost = new HttpPost(path);  
  6.     // Post參數   
  7.     List<NameValuePair> params = new ArrayList<NameValuePair>();  
  8.     params.add(new BasicNameValuePair("id", "helloworld"));  
  9.     params.add(new BasicNameValuePair("pwd", "android"));  
  10.     // 設定字元集   
  11.     HttpEntity entity = new UrlEncodedFormEntity(params, HTTP.UTF_8);  
  12.     // 設定參數實體   
  13.     httpPost.setEntity(entity);  
  14.     // 擷取HttpClient對象   
  15.     HttpClient httpClient = new DefaultHttpClient();  
  16.     // 擷取HttpResponse執行個體   
  17.     HttpResponse httpResp = httpClient.execute(httpPost);  
  18.     // 判斷是夠請求成功   
  19.     if (httpResp.getStatusLine().getStatusCode() == HTTP_200) {  
  20.         // 擷取返回的資料   
  21.         String result = EntityUtils.toString(httpResp.getEntity(), "UTF-8");  
  22.         Log.i(TAG_HTTPGET, "HttpPost方式請求成功,返回資料如下:");  
  23.         Log.i(TAG_HTTPGET, result);  
  24.     } else {  
  25.         Log.i(TAG_HTTPGET, "HttpPost方式請求失敗");  
  26.     }  
  27. }  

相關文章

聯繫我們

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