編輯:關於 Android 程式設計
Android SDK 內建了 Apache HttpClient 模組,早期幾乎所有 App 的網路溝通都建立在它之上。這裡有個容易混淆的細節:Android 採用的是 HttpClient 4.0,套件名稱為 org.apache.http.*,而非常見的 Jakarta Commons HttpClient 3.x(org.apache.commons.httpclient.*)。上網查資料時若直接複製 3.x 的範例,會發現不少類別與方法對不上,原因就在此。
HttpClient 最常搭配 HttpGet 與 HttpPost 使用,分別對應 HTTP 的 GET 與 POST 方法。不論選哪一個,流程都是同樣的三步:
HttpGet 或 HttpPost 物件,把請求的 URL 透過建構子傳入。DefaultHttpClient.execute() 送出請求,取得 HttpResponse 物件。HttpResponse.getEntity() 取得回應內容並做後續處理。若使用 POST,還需在第二步之前多一個動作:以 setEntity() 設定請求參數,參數必須包裝成 NameValuePair 的清單。
// HttpGet 方式請求
public static void requestByHttpGet() throws Exception {
String path = "https://reg.163.com/logins.jsp?id=helloworld&pwd=android";
// 1. 建立 HttpGet 物件
HttpGet httpGet = new HttpGet(path);
// 2. 送出請求
HttpClient httpClient = new DefaultHttpClient();
HttpResponse httpResp = httpClient.execute(httpGet);
// 3. 處理回應
if (httpResp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
String result = EntityUtils.toString(httpResp.getEntity(), "UTF-8");
Log.i(TAG_HTTPGET, "HttpGet 請求成功,回傳內容如下:");
Log.i(TAG_HTTPGET, result);
} else {
Log.i(TAG_HTTPGET, "HttpGet 請求失敗");
}
}
另一種較精簡的寫法,把請求物件建立與 execute 串在一起,並在失敗時主動中止連線:
public String doGet() {
String uriAPI = "https://XXXXX?str=I+am+get+String";
String result = "";
HttpGet httpRequst = new HttpGet(uriAPI);
try {
// HttpGet 是 HttpUriRequest 的子類
HttpResponse httpResponse = new DefaultHttpClient().execute(httpRequst);
if (httpResponse.getStatusLine().getStatusCode() == 200) {
HttpEntity httpEntity = httpResponse.getEntity();
result = EntityUtils.toString(httpEntity);
// 移除回傳字串中的 "\r",否則顯示時尾端會出現一個小方塊
result = result.replaceAll("\r", "");
} else {
httpRequst.abort();
}
} catch (ClientProtocolException e) {
e.printStackTrace();
result = e.getMessage().toString();
} catch (IOException e) {
e.printStackTrace();
result = e.getMessage().toString();
}
return result;
}
POST 的差異在於參數不放在網址列,而是透過 UrlEncodedFormEntity 編碼後塞進 entity。字元集務必明確指定為 UTF-8,否則中文參數會出現亂碼。
public String doPost() {
String uriAPI = "https://XXXXXX"; // POST 的參數不寫在網址上
String result = "";
// 1. 建立 HttpPost 物件
HttpPost httpRequst = new HttpPost(uriAPI);
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("str", "I am Post String"));
try {
httpRequst.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
HttpResponse httpResponse = new DefaultHttpClient().execute(httpRequst);
if (httpResponse.getStatusLine().getStatusCode() == 200) {
HttpEntity httpEntity = httpResponse.getEntity();
result = EntityUtils.toString(httpEntity);
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
result = e.getMessage().toString();
} catch (ClientProtocolException e) {
e.printStackTrace();
result = e.getMessage().toString();
} catch (IOException e) {
e.printStackTrace();
result = e.getMessage().toString();
}
return result;
}
若偏好一次寫完、不做封裝,可以參考這個版本:
// HttpPost 方式請求
public static void requestByHttpPost() throws Exception {
String path = "https://reg.163.com/logins.jsp";
HttpPost httpPost = new HttpPost(path);
// POST 參數
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("id", "helloworld"));
params.add(new BasicNameValuePair("pwd", "android"));
// 指定字元集
HttpEntity entity = new UrlEncodedFormEntity(params, HTTP.UTF_8);
httpPost.setEntity(entity);
HttpClient httpClient = new DefaultHttpClient();
HttpResponse httpResp = httpClient.execute(httpPost);
if (httpResp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
String result = EntityUtils.toString(httpResp.getEntity(), "UTF-8");
Log.i(TAG_HTTPGET, "HttpPost 請求成功,回傳內容如下:");
Log.i(TAG_HTTPGET, result);
} else {
Log.i(TAG_HTTPGET, "HttpPost 請求失敗");
}
}
記得加網路權限。AndroidManifest.xml 中必須宣告 <uses-permission android:name="android.permission.INTERNET" />,否則會直接抛出 UnknownHostException。
不能在主執行緒上請求。Android 3.0(Honeycomb)以後強制執行的 StrictMode 會攔截主執行緒的網路 I/O 並丟出 NetworkOnMainThreadException。上述範例都應包在 AsyncTask、自建 Thread 或(現代做法)ExecutorService/Kotlin 協程之中執行,再把結果回傳主執行緒更新 UI。
記得釋放連線與串流。用完 HttpEntity 應呼叫 consumeContent()(4.0 版)或關閉 InputStream,否則連線池會被佔满導致後續請求阻塞。
現行專案的建議。Apache HttpClient 已在 Android 5.1(API 22)之後被標記為 deprecated 並於後續版本移除,Google 官方推薦改用 HttpURLConnection,或直接使用 OkHttp、Retrofit 這類成熟函式庫。若你是在維護老專案,本文的邏輯仍完全適用;若是新專案,建議把「三步驟」的心智模型帶到新工具上——建立請求、送出、解析回應——概念並沒有改變。
完整攻略:將 Eclipse 專案導入 Android Studio 的兩種方式
只要用過 Android Studio,除了從零開始的新專案,幾乎每個人都會遇到同一個難題:手邊那堆 Eclipse 時代的舊程式碼,究竟該怎麼搬進 Android St
Android 仿當樂遊戲詳情頁(二):布局搭建與移動動畫實作
寫在前面 承接上一篇對當樂遊戲詳情頁的分析,我們已經釐清了它的整體設計思路,本篇要動手把頁面的基本視覺效果做出來,重點落在布局的層次安排與內容區的移動動畫上。 頁面布局
解決 Android Studio 代理隧道 400 Bad Request 的 Gradle 設定方法
問題描述 更新 Android Studio 後,導入新專案時出現 Error: Unable to tunnel through proxy. Proxy return
Android 跨執行緒通訊狀態框架 Simple2Develop 詳解
基本資訊 Simple2Develop 是一款基於 Android 平台的跨執行緒通訊框架,能讓你以簡單的方式完成複雜的通訊,支援同行程中多個 Activity 之間的即