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

Android 學習指南之三十:用 URLConnection 與 HttpClient 抓取網路資料

編輯:關於 Android 開發

上一節我們靠 WebView 這個現成元件把網頁塞進 App 裡,說到底它只負責「顯示」。這一節換個思路:直接用程式碼跟伺服器打交道。用程式碼發請求靈活得多——要帶自訂標頭、要拼接查詢參數、要解析回傳的 XML 或 JSON,全都在自己的掌控之中。

本文要介紹兩套工具:JDK 原生的 URLConnection(實務上多半會轉型成它的子類別 HttpURLConnection),以及 Apache 提供的 HttpClient 元件。

兩者的定位差在哪

有趣的是,這兩種寫法在 Android 上的用法,跟 Java Web 開發裡幾乎一模一樣。也就是說,你先前在伺服器端累積的經驗可以直接搬過來;反過來,學完這一節之後再去翻 Java Web 的資料,特別是 HttpClient 4.0 那一整套 API,能幫助你把底層機制看得更透徹。

簡單比較一下:HttpURLConnection 屬於 Java 標準庫,物件輕、可控性高,適合大多數情境;HttpClient 則封裝了連線池、Cookie 管理、重試機制等進階功能,功能齊全但結構較重。

實作範例:抓取 Google 天氣服務

這個範例的目標很單純:從 Google 天氣 API 取得鄭州的預報資料,把回傳的 XML 原封不動丟進 TextView 顯示出來。本節先不做任何美化,畫面確實很醜,等下一節學完 XML 解析,我們再把它做成圖文並茂的天氣卡片,敬請忍耐一下。

步驟一:建立專案

新增專案 Lesson30_HttpClient,主 Activity 命名為 MainActivity.java。

步驟二:撰寫版面配置 res/layout/main.xml

畫面上放兩個按鈕,分別觸發兩種連線方式,下方用 ScrollView 包住 TextView 以便承載篇幅很長的 XML:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical">

    <TextView
        android:id="@+id/TextView01"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="網路連線測試" />

    <Button
        android:id="@+id/Button01"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="使用 URLConnection 訪問 GoogleWeatherAPI" />

    <Button
        android:id="@+id/Button02"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="使用 HttpClient 訪問 GoogleWeatherAPI" />

    <ScrollView
        android:id="@+id/ScrollView01"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">
        <TextView
            android:id="@+id/TextView02"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
    </ScrollView>
</LinearLayout>

步驟三:撰寫 MainActivity.java

package android.basic.lesson30;

import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {

    TextView tv;

    String googleWeatherUrl1 = "https://www.google.com/ig/api?weather=zhengzhou";
    String googleWeatherUrl2 = "https://www.google.com/ig/api?hl=zh-cn&weather=zhengzhou";

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        // 定義 UI 元件
        Button b1 = (Button) findViewById(R.id.Button01);
        Button b2 = (Button) findViewById(R.id.Button02);
        tv = (TextView) findViewById(R.id.TextView02);

        // 設定按鈕單擊監聽器:走 URLConnection
        b1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                urlConn();
            }
        });

        // 設定按鈕單擊監聽器:走 HttpClient
        b2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                httpClientConn();
            }
        });
    }

    // 使用 URLConnection 連接 Google Weather API
    protected void urlConn() {
        try {
            // 包裝成 URL 物件
            URL url = new URL(googleWeatherUrl1);
            // 取得 HttpURLConnection
            HttpURLConnection httpconn = (HttpURLConnection) url.openConnection();

            if (httpconn.getResponseCode() == HttpURLConnection.HTTP_OK) {
                Toast.makeText(getApplicationContext(), "連接 Google Weather API 成功!",
                        Toast.LENGTH_SHORT).show();

                // 指定 UTF-8 讀取串流,避免中文變亂碼
                InputStreamReader isr = new InputStreamReader(httpconn.getInputStream(), "utf-8");
                int i;
                String content = "";
                // 逐字元讀取
                while ((i = isr.read()) != -1) {
                    content = content + (char) i;
                }
                isr.close();
                tv.setText(content);
            }
            // 用完記得釋放連線
            httpconn.disconnect();
        } catch (Exception e) {
            Toast.makeText(getApplicationContext(), "連接 Google Weather API 失敗", Toast.LENGTH_SHORT)
                    .show();
            e.printStackTrace();
        }
    }

    // 使用 HttpClient 連接 Google Weather API
    protected void httpClientConn() {
        // 建立用戶端
        DefaultHttpClient httpclient = new DefaultHttpClient();
        // 建立 GET 請求
        HttpGet httpget = new HttpGet(googleWeatherUrl2);
        // 用 ResponseHandler 直接把結果收斂成字串
        ResponseHandler<String> responseHandler = new BasicResponseHandler();

        try {
            String content = httpclient.execute(httpget, responseHandler);
            Toast.makeText(getApplicationContext(), "連接 Google Weather API 成功!",
                    Toast.LENGTH_SHORT).show();
            tv.setText(content);
        } catch (Exception e) {
            Toast.makeText(getApplicationContext(), "連接 Google Weather API 失敗", Toast.LENGTH_SHORT)
                    .show();
            e.printStackTrace();
        }
        // 關閉連線管理器
        httpclient.getConnectionManager().shutdown();
    }
}

兩段程式碼的對照很值得玩味:urlConn() 需要你自己管理串流、自己指定編碼、自己收尾;httpClientConn() 只要把 BasicResponseHandler 交給 execute(),回來的就是一個現成的字串,乾淨俐落。

步驟四:别忘了加上網路權限

在 AndroidManifest.xml 中補上這一行,否則程式會直接丟出安全例外:

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

步驟五:編譯執行

按下第一個按鈕,走 URLConnection 的路線,回傳的 XML 原始碼被塞進了 TextView:

按下第二個按鈕,改走 HttpClient,畫面結構一模一樣,差別只在網址多帶了 hl=zh-cn 參數,因此顯示出來的是中文內容。

幾個實務上一定要知道的眉角

主執行緒不能連線

從 Android 3.0(API 11)開始,若在 UI 執行緒上發起網路請求,系統會直接丟出 NetworkOnMainThreadException。上面範例之所以能在舊環境跑起來,是因為它寫在早期版本上;新專案請務必把網路操作丟到子執行緒,再透過 Handler 回報結果——這正是下一節的主題。

資源一定要關

HttpURLConnection 用完要 disconnect(),DefaultHttpClient 則要呼叫 getConnectionManager().shutdown(),否則連線會一直被佔著。

字串累加是效能陷阱

範例中的 content = content + (char) i 為了教學好懂而寫得直白,但每次累加都會產生新的字串物件。資料量一大就該改用 StringBuilder。

HttpClient 已被淘汰

Apache HttpClient 自 API 22 起被標記為 deprecated,Google 官方文件建議改用 HttpURLConnection。理解它的設計仍有價值,但新專案請優先選擇 HttpURLConnection,或是功能更完整的 OkHttp 這類第三方庫。

這一節我們把兩條路都走過一遍,也順手把該注意的坑標出來。下一節進入 XML 解析,我們把這個醜陋的文字畫面徹底改造成真正的天氣預報介面。

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