編輯:關於 Android 開發
在先前的〈Android 採用 get 方式提交資料到伺服器〉〈Android 採用 post 方式提交資料到伺服器〉〈Android 採用 HttpClient 提交資料到伺服器〉幾篇中,已介紹過兩種把資料提交到伺服器的方法。本文則介紹另一種基於 android-async-http 框架的實作。
android-async-http 是一個強大的第三方開源網路請求庫,它建立在 Apache HttpClient 之上,所有網路處理都基於 Android 的非 UI 執行緒,並透過回呼方法處理請求結果。
官網源碼:https://github.com/loopj/android-async-http
官網教學:https://loopj.com/android-async-http/
建立專案後,先到 GitHub 下載對應的 zip 檔,解壓縮後將 src 中的 com 資料夾複製到專案的 src 目錄。

使用 android-async-http 框架的程式碼如下,可見程式碼量大幅減少:
package com.wuyudong.asynchttp;
import java.net.URLEncoder;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.widget.Toast;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void click(View view) {
// 用戶名密碼提交到服務器
AsyncHttpClient client = new AsyncHttpClient();
String path = "https://169.254.168.71:8080/web/LoginServlet?username="
+ URLEncoder.encode("wuyudong") + "&password=" + URLEncoder.encode("123");
client.get(path, new AsyncHttpResponseHandler() {
@Override
public void onSuccess(String content) {
super.onSuccess(content);
Toast.makeText(MainActivity.this, "請求成功!", 0).show();
}
@Override
public void onFailure(Throwable error, String content) {
super.onFailure(error, content);
Toast.makeText(MainActivity.this, "請求失敗!", 0).show();
}
});
}
}
下面來實作一個精簡版的異步框架,理解其原理。

AsyncHttpClient.java:核心是在子執行緒中發起 HTTP 請求,完成後透過 Handler 回傳訊息。
package com.wuyudong.AsyncClient;
import java.io.InputStream;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import android.os.Message;
public class AsyncHttpClient {
public void get(final String path, final MyHandler myHandler) {
new Thread() {
@Override
public void run() {
HttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(path);
try {
HttpResponse response = client.execute(httpGet);
InputStream is = response.getEntity().getContent();
String content = StreamTools.readInputStream(is);
// 執行成功
Message msg = new Message();
msg.what = 0;
msg.obj = "請求成功";
myHandler.sendMessage(msg);
} catch (Exception e) {
e.printStackTrace();
// 執行失敗
Message msg = new Message();
msg.what = 1;
msg.obj = "請求失敗";
myHandler.sendMessage(msg);
}
}
}.start();
}
}
MainActivity.java:開啟子執行緒執行請求,完成後通知 UI。
package com.wuyudong.AsyncClient;
import java.net.URLEncoder;
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.widget.Toast;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void click(View view) {
AsyncHttpClient client = new AsyncHttpClient();
String path = "https://169.254.168.71:8080/web/LoginServlet?username="
+ URLEncoder.encode("wuyudong") + "&password=" + URLEncoder.encode("123");
client.get(path, new MyHandler() {
@Override
public void onFailure(String content) {
Toast.makeText(MainActivity.this, content, 1).show();
super.onFailure(content);
}
@Override
public void onSuccess(String content) {
Toast.makeText(MainActivity.this, content, 0).show();
super.onSuccess(content);
}
});
}
}
MyHandler.java:根據 msg.what 分派成功或失敗的回呼。
package com.wuyudong.AsyncClient;
import android.os.Handler;
import android.os.Message;
public class MyHandler extends Handler {
public void onFailure(String content) { }
public void onSuccess(String content) { }
@Override
public void handleMessage(Message msg) {
String content = (String) msg.obj;
switch (msg.what) {
case 0:
onSuccess(content);
break;
case 1:
onFailure(content);
break;
default:
break;
}
super.handleMessage(msg);
}
}
StreamTools.java:負責把輸入流的內容轉成字串,並嘗試依編碼解析。
package com.wuyudong.AsyncClient;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
public class StreamTools {
/**
* 把輸入流的內容轉化成字符串
*/
public static String readInputStream(InputStream is) {
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int len = 0;
byte[] buffer = new byte[1024];
while ((len = is.read(buffer)) != -1) {
baos.write(buffer, 0, len);
}
is.close();
baos.close();
byte[] result = baos.toByteArray();
String str = new String(result);
if (str.contains("gb2312")) {
return new String(result, "gb2312");
} else if (str.contains("utf-8")) {
return str;
} else {
return null;
}
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
如此便完成了一個自製的精簡異步 HTTP 框架,其精神與 android-async-http 一致:子執行緒負責網路請求,Handler 負責把結果回送到主執行緒更新 UI。
Android 模擬 iOS 相機模式滑動效果
Android 模擬 iOS 相機模式滑動效果 要在 Android 上做出類似 iOS 相機模式切換的滑動效果,可以嘗試自定義 LinearLayout。目標是讓多個模
Android 屬性動畫入門:ValueAnimator、ObjectAnimator 與插值器
Android 屬性動畫基礎 Android 3.0 之後引入屬性動畫框架。與傳統檢視動畫不同,屬性動畫會實際改變物件屬性,因此動畫與事件狀態能保持一致。 屬性動畫架構
初識 Android:從布局與常用屬性開始
初識 Android:從布局與常用屬性開始 第一次接觸 Android 開發時,可以先從最基礎的布局與元件屬性著手。透過幾個簡單的練習,就能理解畫面是如何被 XML 描述
百度地圖 SDK 快速上手:定位、Marker 與自訂資訊窗
百度地圖 SDK 快速上手:定位、Marker 與自訂資訊窗 最近做了一個百度地圖的 Demo,把過程中踩到的坑整理成一份清單,之後再接入時可以少繞幾圈。 一、容易卡住