Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 網路通訊實戰:HttpGet 與 HttpPost 請求完整示例

編輯:關於 Android 程式設計

在 Android 上與伺服器交換資料,最基礎的方式之一就是透過 HttpClient 發送 HTTP 請求。本文分別用 HttpGet 與 HttpPost 兩個常見場景,示範如何取得伺服器返回的資料並顯示到畫面上。使用前別忘了在 AndroidManifest.xml 中加入網路權限 <uses-permission android:name="android.permission.INTERNET" />。

一、使用 HttpGet 進行通訊

GET 適合把參數直接拼接在 URL 後面的查詢場景:

複製程式碼 程式碼如下:
/**
 *description:Android HttpGet()
 *authour:YanEr·Gates
 *website:https://www.jb51.net
 */
package me.gogogoog; 
import java.io.IOException;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

public class MyHttpGetActivity extends Activity{
 /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState){ 
        super.onCreate(savedInstanceState); 
        setContentView(R.layout.result);
        TextView resultText = (TextView) this.findViewById(R.id.resultText);          
        String username="username"; 
        String password="password"; 
        String httpUrl = "https://192.168.1.90:8080/AndroidLogin/loginAction.do?method=login&username="+username+"&password="+password;   
        //創建httpRequest對象
        HttpGet httpRequest = new HttpGet(httpUrl);
  try
  {
   //取得HttpClient對象
   HttpClient httpclient = new DefaultHttpClient();
   //請求HttpClient,取得HttpResponse
   HttpResponse httpResponse = httpclient.execute(httpRequest);
   //請求成功
   if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK)
   {
    //取得返回的字符串
    String strResult = EntityUtils.toString(httpResponse.getEntity());
    resultText.setText(strResult);
   }
   else
   {
    resultText.setText("請求錯誤!");
   }
  }
  catch (ClientProtocolException e)
  {
   resultText.setText(e.getMessage().toString());
  }
  catch (IOException e)
  {
   resultText.setText(e.getMessage().toString());
  }
  catch (Exception e)
  {
   resultText.setText(e.getMessage().toString());
  }   
    }
}

二、使用 HttpPost 進行通訊

POST 則更適合傳送使用者帳密等較敏感或較長的參數,資料放在請求本文中而非 URL:

複製程式碼 程式碼如下:
/** 
*description:Android HttpPost() 
*authour:YanEr·Gates 
*website:https://www.jb51.net
*/
package me.gogogoog; 
import java.io.IOException; 
import java.util.ArrayList; 
import java.util.List; 
import org.apache.http.HttpEntity; 
import org.apache.http.HttpResponse; 
import org.apache.http.HttpStatus; 
import org.apache.http.NameValuePair; 
import org.apache.http.client.ClientProtocolException; 
import org.apache.http.client.HttpClient; 
import org.apache.http.client.entity.UrlEncodedFormEntity; 
import org.apache.http.client.methods.HttpPost; 
import org.apache.http.impl.client.DefaultHttpClient; 
import org.apache.http.message.BasicNameValuePair; 
import org.apache.http.util.EntityUtils; 
import android.app.Activity; 
import android.widget.TextView; 
public class ResultActivity extends Activity{ 
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState){ 
        super.onCreate(savedInstanceState); 
        setContentView(R.layout.result); 
        TextView resultText = (TextView) this.findViewById(R.id.resultText);                 
        String username="username"; 
        String password="password"; 
        String httpUrl = "https://192.168.1.90:8080/AndroidLogin/loginAction.do?method=login"; 
        //創建httpRequest對象 
        HttpPost httpRequest = new HttpPost(httpUrl); 
        List<NameValuePair> params = new ArrayList<NameValuePair>(); 
        params.add(new BasicNameValuePair("username", username)); 
        params.add(new BasicNameValuePair("password", password)); 
        try{ 
             //設置字符集 
            HttpEntity httpentity = new UrlEncodedFormEntity(params, "gb2312"); 
            //請求httpRequest 
            httpRequest.setEntity(httpentity); 
            //取得默認的HttpClient 
            HttpClient httpclient = new DefaultHttpClient(); 
            //取得HttpResponse 
            HttpResponse httpResponse = httpclient.execute(httpRequest); 
            //HttpStatus.SC_OK表示連接成功 
            if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK){ 
                //取得返回的字符串 
                String strResult = EntityUtils.toString(httpResponse.getEntity()); 
                resultText.setText(strResult); 
            }else{ 
                resultText.setText("請求錯誤!"); 
            } 
        }catch (ClientProtocolException e){ 
            resultText.setText(e.getMessage().toString()); 
        } catch (IOException e){ 
            resultText.setText(e.getMessage().toString()); 
        }catch (Exception e){ 
            resultText.setText(e.getMessage().toString()); 
        }  
    } 
}

兩段程式碼的共同套路是:建立請求物件 → 用 DefaultHttpClient 執行 → 判斷狀態碼是否為 SC_OK → 以 EntityUtils.toString 取出回應字串。差別在於 GET 把參數拼進 URL,而 POST 透過 NameValuePair 清單與 UrlEncodedFormEntity 把參數編碼進本文。

實務提醒:在 Android 4.0 以後,主執行緒不能直接進行網路操作,否則會拋出 NetworkOnMainThreadException。因此實際開發時,請把上述網路請求放到 AsyncTask、Thread 或 Kotlin 協程等非主執行緒中執行,並透過 Handler 等方式把結果回傳到 UI 執行緒更新畫面。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved