編輯:關於 Android 程式設計
上一篇講了 URLConnection,它能很方便地與指定站點交換信息。它還有一個專為 HTTP 場景增強的子類——HttpURLConnection,在基礎上補充了一批操作 HTTP 資源的便捷方法。
setRequestMethod(String) // 設置請求方法
getResponseCode() // 獲取服務器響應碼
getResponseMessage() // 獲取響應消息
GET 請求:
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(8000); // 連接超時
conn.setReadTimeout(8000); // 讀取超時
POST 請求:
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
釋放連接:
if (conn != null) conn.disconnect();
// ① 把地址封裝成 URL 對象
URL url = new URL(String spec);
// ② 獲取連接對象(此時尚未真正連接)
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
// ③ 初始化連接參數
conn.setRequestMethod("GET");
conn.setConnectTimeout(5000);
conn.setReadTimeout(5000);
// ④ 建立連接
conn.connect();
// ⑤ 獲取響應流
InputStream is = conn.getInputStream();
// ⑥ 按需處理流中的數據(字符串、圖片等)
這個例子加了一個小技巧:首次加載網絡圖片時順手寫入本地緩存,之後直接從緩存讀取,省掉重複的網絡請求。

布局:
<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:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="onClick"
android:text="加載圖片" />
<ImageView
android:id="@+id/iv"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
核心邏輯:
public class MainActivity extends Activity {
private ImageView iv;
private String path = "https://example.com/logo.png";
public static final int SUCCESS = 0x1;
public static final int FAIL = 0x0;
private Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case SUCCESS:
iv.setImageBitmap((Bitmap) msg.obj);
break;
case FAIL:
Toast.makeText(MainActivity.this, "請求失敗",
Toast.LENGTH_LONG).show();
break;
}
}
};
public void onClick(View view) {
final File cacheFile = new File(getCacheDir(), "a2.jpg");
if (cacheFile.exists()) {
Bitmap bitmap = BitmapFactory.decodeFile(
cacheFile.getAbsolutePath());
iv.setImageBitmap(bitmap);
} else {
new Thread() {
@Override
public void run() {
try {
URL url = new URL(path);
HttpURLConnection conn =
(HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(5000);
conn.setReadTimeout(5000);
conn.connect();
if (conn.getResponseCode() == 200) {
InputStream is = conn.getInputStream();
// 寫入本地緩存
FileOutputStream fos =
new FileOutputStream(cacheFile);
byte[] b = new byte[1024];
int len;
while ((len = is.read(b)) != -1) {
fos.write(b, 0, len);
}
fos.flush();
fos.close();
Bitmap bitmap = BitmapFactory.decodeFile(
cacheFile.getAbsolutePath());
Message msg = Message.obtain();
msg.what = SUCCESS;
msg.obj = bitmap;
mHandler.sendMessage(msg);
} else {
Message msg = Message.obtain();
msg.what = FAIL;
mHandler.sendMessage(msg);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}.start();
}
}
}
注意幾個細節:網絡請求在子線程執行;結果通過 Handler 回到主線程更新 UI;getCacheDir() 是應用私有緩存目錄,系統在空間緊張時可以清理,適合放這類可重新下載的數據。
Android 5.0 之前 HttpClient 是主流選擇,5.0 之後被 HttpURLConnection 取代,6.0 中則被完全移除。它由 Apache 提供,功能與 HttpURLConnection 幾乎重合,但用法差異很大。
為什麼曾經流行?如果只是向一個簡單頁面發請求並讀響應,HttpURLConnection 綽綽有餘。但真實的 Web 站點往往沒這麼簡單:需要登錄、需要權限、需要維持會話狀態。這時就要處理 Session 和 Cookie,而 HttpClient 在這方面提供了更完善的支持。
它與瀏覽器的區別: HttpClient 只是一個 HTTP 客戶端,不是瀏覽器。它能發請求、收響應,但不會緩存響應、不執行頁面中嵌入的 JavaScript、也不解析 HTML。它會自動維護與服務器之間的 Session 狀態,前提是使用同一個 HttpClient 對象發送多次請求。
// a) 創建 HttpClient
HttpClient client = new DefaultHttpClient();
// b) 根據需要創建 Get 或 Post 對象
HttpGet get = new HttpGet(url);
HttpPost post = new HttpPost(url);
// c) 添加請求參數
List<NameValuePair> params = new ArrayList<>();
params.add(new BasicNameValuePair("name", name));
params.add(new BasicNameValuePair("pwd", pwd));
post.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
// d) 發送請求
HttpResponse response = client.execute(post);
// e) 解析響應
int code = response.getStatusLine().getStatusCode(); // 200 表示成功
HttpEntity entity = response.getEntity();
String result = EntityUtils.toString(entity, "UTF-8");
HttpClient 可以返回多種格式的數據,需要區分處理:
EntityUtils.toString() 轉字符串;三種常見處理方式:
// 1. 對參數編碼
String n = URLEncoder.encode("張三", "UTF-8");
// 2. 從字節數組還原(該方式已過時)
String n = EncodingUtils.getString("張三".getBytes(), "UTF-8");
// 3. 顯式指定請求頭字符集
conn.setRequestProperty("Charset", "UTF-8");
HttpClient 在 5.1 時已被標記為過時,官方不再推薦;6.0 中直接被移除。如果維護老項目必須使用,需要把編譯配置調整到相應版本,或者直接引入 Apache 官方提供的獨立 httpclient 依賴。新項目請直接使用 HttpURLConnection 或 OkHttp 等現代方案。
Android pullToRefresh 下拉刷新庫的導入與使用心得
pullToRefresh 的導入首先點擊 New 按鈕,選擇 Import Module。接著在 New Module 介面中,選擇本機已含源碼的 pullToRefr
Android 源碼解析(十九):Dialog 的加載與繪制流程
前面兩篇我們拆解了 Activity 的布局加載與繪制流程,對系統界面的顯示機制算是有了整體認識。其實 Android 中所有顯示控件的流程都大同小異——Dialog、P
Android 自定義控件實戰:打造可複用的標題欄組合控件(自定義屬性 + 接口回調)
前面我們聊過其中一種自定義 View 的做法(音頻條)。那篇的建議今天仍然有效:一次只學會一種技術,看完自己動手做一遍,再試著加點功能擴展,比一次吞五篇有用得多。 今天
Android 動畫開發實踐:View 動畫、屬性動畫與幀動畫
動畫讓介面更有生命力 好的動畫能讓操作更直覺,也能降低畫面切換的生硬感。Android 常見動畫可分為 View 動畫、屬性動畫與幀動畫,三者適用場景不同。 View 動