編輯:關於 Android 程式設計
在 Android 平台上發送 HTTP 請求,常見的做法有兩種:HttpURLConnection 與 HttpClient。本文將透過一個完整的範例,帶你分別掌握這兩種方式。
取得 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 是 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 的基本用法都了然於心了。
Material Design 深入實踐:用自定義 Behavior 打造上滑顯示的返回頂部按鈕
效果預覽完整源碼附於文末。為什麼需要一個「回到頂部」按鈕當頁面內容特別長時,使用者滑到最底部後,若想把畫面拉回頂端往往得反覆滑動,體驗相當折磨。Android 不像 iO
Android 開發:ContentProvider 與 Uri 詳解
十二、ContentProvider 與 Uri 詳解 一、使用 ContentProvider(內容提供者)共享資料 ContentProvider 在 Android
Android UI 適配限定符完全整理
Android 應用常需要面對不同尺寸、解析度、方向與語言環境的裝置。若只依賴單一版面,容易出現配置錯誤或顯示不理想。限定符(Qualifier)的出現,讓開發者可以針對
Android 效能優化實務:快取策略、資料結構與延遲載入
延續先前談過的版面優化,本篇把焦點放在編碼細節層面的效能優化。程式碼的寫法對執行效率影響甚鉅,以下依三個主題展開:快取、資料(型別與結構)、以及延遲/優先載入。 一、快