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

Android 網路通訊入門:HttpURLConnection 與 HttpClient 實戰

編輯:關於 Android 程式設計

在 Android 平台上發送 HTTP 請求,常見的做法有兩種:HttpURLConnection 與 HttpClient。本文將透過一個完整的範例,帶你分別掌握這兩種方式。

一、使用 HttpURLConnection

取得 HttpURLConnection 實例很簡單,只要 new 一個 URL 物件並傳入目標位址,再呼叫 openConnection() 即可:

URL url = new URL("https://www.baidu.com");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();

接著設定請求方法,最常見的是 GET(取得資料)與 POST(提交資料):

connection.setRequestMethod("GET");
connection.setConnectTimeout(8000);
connection.setReadTimeout(8000);
InputStream in = connection.getInputStream();   // 取得伺服器回傳的輸入流
connection.disconnect();                         // 使用完畢後關閉連線

版面配置:由於手機螢幕空間有限,內容過多時無法在一個畫面內顯示,這裡用 ScrollView 讓使用者得以捲動瀏覽;同時放置一個 Button 用來發送請求,一個 TextView 用來顯示回傳結果。

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
    <Button android:id="@+id/send_request"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="send request" />
    <ScrollView android:layout_width="match_parent"
        android:layout_height="match_parent" >
        <TextView android:id="@+id/response_text"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />
    </ScrollView>
</LinearLayout>

MainActivity 關鍵程式碼:由於子線程無法直接操作 UI,因此這裡透過 Handler + Message 的機制,把伺服器回傳的內容送回主線程顯示。

public class MainActivity extends Activity implements OnClickListener {
    public static final int SHOW_RESPONSE = 0;
    private Button sendRequest;
    private TextView responseText;

    private Handler handler = new Handler() {
        @Override public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case SHOW_RESPONSE:
                    responseText.setText((String) msg.obj);
                    break;
                default: break;
            }
        }
    };

    @Override protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        sendRequest = (Button) findViewById(R.id.send_request);
        responseText = (TextView) findViewById(R.id.response_text);
        sendRequest.setOnClickListener(this);
    }

    @Override public void onClick(View v) {
        if (v.getId() == R.id.send_request) {
            sendRequestWithHttpURLConnection();
        }
    }

    private void sendRequestWithHttpURLConnection() {
        new Thread(new Runnable() {
            @Override public void run() {
                HttpURLConnection connection = null;
                try {
                    URL url = new URL("https://www.baidu.com");
                    connection = (HttpURLConnection) url.openConnection();
                    connection.setRequestMethod("GET");
                    connection.setConnectTimeout(8000);
                    connection.setReadTimeout(8000);
                    InputStream in = connection.getInputStream();
                    BufferedReader reader = new BufferedReader(new InputStreamReader(in));
                    StringBuilder response = new StringBuilder();
                    String line;
                    while ((line = reader.readLine()) != null) {
                        response.append(line);
                    }
                    Message message = new Message();
                    message.what = SHOW_RESPONSE;
                    message.obj = response.toString();
                    handler.sendMessage(message);
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    if (connection != null) connection.disconnect();
                }
            }
        }).start();
    }
}

點擊 send request 按鈕後,程式會開啟一個子線程發出請求,並用 BufferedReader 讀取回傳的資料流,最後透過 Handler 把結果送回主線程更新 TextView。

別忘了加上網路權限:

<uses-permission android:name="android.permission.INTERNET"/>

執行後點擊按鈕,就能看到百度首頁的內容顯示出來:

若要改用 POST 提交參數,只需調整請求方法並寫入輸出流:

connection.setRequestMethod("POST");
DataOutputStream out = new DataOutputStream(connection.getOutputStream());
out.writeBytes("username=admin&password=123456");

二、使用 HttpClient

HttpClient 是 Apache 提供的 HTTP 網路存取介面,早在 Android 初期就被納入 API。它能完成與 HttpURLConnection 幾乎相同的效果,但用法差異不小。

由於 HttpClient 是一個介面,無法直接建立實例,通常會 new 一個 DefaultHttpClient:

HttpClient httpClient = new DefaultHttpClient();

GET 請求:建立 HttpGet 物件並傳入位址,再呼叫 execute():

HttpGet httpGet = new HttpGet("https://www.baidu.com");
httpClient.execute(httpGet);

POST 請求:建立 HttpPost 物件,透過 NameValuePair 集合存放參數,再包裝成 UrlEncodedFormEntity:

HttpPost httpPost = new HttpPost("https://www.baidu.com");
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("username", "jack"));
params.add(new BasicNameValuePair("password", "123456"));
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params, "utf-8");
httpPost.setEntity(entity);
httpClient.execute(httpPost);

執行 execute() 後會回傳一個 HttpResponse,伺服器的所有回應都包含在裡面。通常先檢查狀態碼是否為 200,再取出內容:

if (httpResponse.getStatusLine().getStatusCode() == 200) {
    HttpEntity entity = httpResponse.getEntity();
    // 若回傳含中文,指定 utf-8 可避免亂碼
    String response = EntityUtils.toString(entity, "utf-8");
}

把範例專案改用 HttpClient 實作,只需在 MainActivity 中新增一個方法:

private void sendRequestWithHttpClient() {
    new Thread(new Runnable() {
        @Override public void run() {
            try {
                HttpClient httpClient = new DefaultHttpClient();
                HttpGet httpGet = new HttpGet("https://www.baidu.com");
                HttpResponse httpResponse = httpClient.execute(httpGet);
                if (httpResponse.getStatusLine().getStatusCode() == 200) {
                    HttpEntity entity = httpResponse.getEntity();
                    String response = EntityUtils.toString(entity, "utf-8");
                    Message message = new Message();
                    message.what = SHOW_RESPONSE;
                    message.obj = response;
                    handler.sendMessage(message);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }).start();
}

版面配置完全不必更動,重新執行後點擊按鈕,你會發現結果與先前一致,這也證明 HttpClient 的請求方式同樣奏效。練習至此,你應該已經對 HttpURLConnection 與 HttpClient 的基本用法都了然於心了。

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