編輯:關於 Android 開發
上一節我們靠 WebView 這個現成元件把網頁塞進 App 裡,說到底它只負責「顯示」。這一節換個思路:直接用程式碼跟伺服器打交道。用程式碼發請求靈活得多——要帶自訂標頭、要拼接查詢參數、要解析回傳的 XML 或 JSON,全都在自己的掌控之中。
本文要介紹兩套工具:JDK 原生的 URLConnection(實務上多半會轉型成它的子類別 HttpURLConnection),以及 Apache 提供的 HttpClient 元件。
有趣的是,這兩種寫法在 Android 上的用法,跟 Java Web 開發裡幾乎一模一樣。也就是說,你先前在伺服器端累積的經驗可以直接搬過來;反過來,學完這一節之後再去翻 Java Web 的資料,特別是 HttpClient 4.0 那一整套 API,能幫助你把底層機制看得更透徹。
簡單比較一下:HttpURLConnection 屬於 Java 標準庫,物件輕、可控性高,適合大多數情境;HttpClient 則封裝了連線池、Cookie 管理、重試機制等進階功能,功能齊全但結構較重。
這個範例的目標很單純:從 Google 天氣 API 取得鄭州的預報資料,把回傳的 XML 原封不動丟進 TextView 顯示出來。本節先不做任何美化,畫面確實很醜,等下一節學完 XML 解析,我們再把它做成圖文並茂的天氣卡片,敬請忍耐一下。
新增專案 Lesson30_HttpClient,主 Activity 命名為 MainActivity.java。
畫面上放兩個按鈕,分別觸發兩種連線方式,下方用 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>
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。
Apache HttpClient 自 API 22 起被標記為 deprecated,Google 官方文件建議改用 HttpURLConnection。理解它的設計仍有價值,但新專案請優先選擇 HttpURLConnection,或是功能更完整的 OkHttp 這類第三方庫。
這一節我們把兩條路都走過一遍,也順手把該注意的坑標出來。下一節進入 XML 解析,我們把這個醜陋的文字畫面徹底改造成真正的天氣預報介面。
Android 開發實戰(九):五大佈局全解析——線性、相對、框架、絕對與表格
介面是使用者對一個 App 的第一印象,而佈局決定了介面的骨架。這一節把 Android 最基礎的五種佈局逐一拆開來看,順便說清楚該在什麼場合用哪一種。 一、線性佈局(L
Android Studio 開發環境建置與 Android 專案建立指南
Android Studio 開發環境建置與 Android 專案建立 本文以 Mac 環境為例,整理 Android 開發的初始設定流程。整體概念與 Windows 類
Nagios 分組出圖的程式碼實現(下):讓同組主機的服務圖一次畫完
承接上篇:從「選得中」到「畫得出」上一節我們完成了分組全選:沿用 Nagios 自帶的主機/服務分組,在列表裡補上複選框,讓同一組的機器可以一次勾選,並加上服務分類的下拉
Android 登入客戶端實戰:驗證碼抓取、網頁資料解析與 HttpWatch 抓包入門
在行動網路無所不在的今天,一個不連網的 App 很難有長遠生命週期,因此網路程式設計是每個 Android 開發者的必修課。這篇以「模擬登入學校教務系統」為案例,完整走一