編輯:關於 Android 程式設計
在 Android 上存取 HTTP 服務,除了 java.net 這條路,Android SDK 還內建了 Apache 的 HttpClient。它對 HTTP 協定有相當完整的支援,GET 與 POST 都能勝任。本文以一個實際專案走過三種典型情境:文字參數的 GET、表單式的 POST,以及 multipart 檔案上傳。

這個專案刻意不寫任何 Activity,所有操作都放在單元測試類別 HttpTest.java 中完成,這樣可以直接驗證網路邏輯而不受 UI 干擾。
所有設定都在 AndroidManifest.xml 完成:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
package="com.scott.http"
android:versionCode="1"
android:versionName="1.0">
<application android:icon="@drawable/icon" android:label="@string/app_name">
<!-- 載入測試用的函式庫 -->
<uses-library android:name="android.test.runner"/>
</application>
<!-- 指定測試執行器與目標套件 -->
<instrumentation
android:name="android.test.InstrumentationTestRunner"
android:targetPackage="com.scott.http"/>
<!-- 網路權限,少了這行一切都會失敗 -->
<uses-permission android:name="android.permission.INTERNET"/>
<uses-sdk android:minSdkVersion="8" />
</manifest>
測試類別需繼承 android.test.AndroidTestCase。它本身繼承自 junit 的 TestCase,額外提供了 getContext()——這在 Android 開發中格外有用,因為大量 API 都需要 Context 才能運作。
public class HttpTest extends AndroidTestCase {
private static final String PATH = "https://192.168.1.57:8080/web";
/** 案例一:GET 請求 */
public void testGet() throws Exception {
HttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet(PATH + "/TestServlet?id=1001&name=john&age=60");
HttpResponse response = client.execute(get);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
InputStream is = response.getEntity().getContent();
String result = inStream2String(is);
Assert.assertEquals("GET_SUCCESS", result);
}
}
/** 案例二:POST 表單 */
public void testPost() throws Exception {
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(PATH + "/TestServlet");
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("id", "1001"));
params.add(new BasicNameValuePair("name", "john"));
params.add(new BasicNameValuePair("age", "60"));
post.setEntity(new UrlEncodedFormEntity(params));
HttpResponse response = client.execute(post);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
String result = inStream2String(response.getEntity().getContent());
Assert.assertEquals("POST_SUCCESS", result);
}
}
/** 案例三:multipart 檔案上傳 */
public void testUpload() throws Exception {
InputStream is = getContext().getAssets().open("books.xml");
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(PATH + "/UploadServlet");
MultipartEntity multipartEntity = new MultipartEntity();
multipartEntity.addPart("file", new InputStreamBody(is, "books.xml"));
multipartEntity.addPart("desc", new StringBody("this is description."));
post.setEntity(multipartEntity);
HttpResponse response = client.execute(post);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
String result = inStream2String(response.getEntity().getContent());
Assert.assertEquals("UPLOAD_SUCCESS", result);
}
}
/** 把輸入流轉為字串 */
private String inStream2String(InputStream is) throws Exception {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
int len;
while ((len = is.read(buf)) != -1) {
baos.write(buf, 0, len);
}
return new String(baos.toByteArray());
}
}
一個關鍵細節:伺服器位址必須用 IP,不能寫 localhost。因為服務端跑在 Windows 上,而測試跑在 Android 模擬器中,localhost 指的是模擬器自己,顯然找不到服務。
參數直接附加在網址後面,由 Servlet 的 doGet 接收:
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String id = request.getParameter("id");
String name = request.getParameter("name");
String age = request.getParameter("age");
System.out.println("id:" + id + ", name:" + name + ", age:" + age);
response.getWriter().write("GET_SUCCESS");
}
POST 的參數不寫在網址上,而是打包成 NameValuePair 集合,經 UrlEncodedFormEntity 編碼後交給 setEntity():
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String id = request.getParameter("id");
String name = request.getParameter("name");
String age = request.getParameter("age");
System.out.println("id:" + id + ", name:" + name + ", age:" + age);
response.getWriter().write("POST_SUCCESS");
}
GET 與 POST 只能送文字,要上傳檔案就必須走 multipart/form-data。Android 內附的 HttpClient 版本不支援這種請求,因此需要引入 Apache 的 HttpMime 元件(屬於 HttpComponents 專案)。到 Apache 官網下載 HttpComponents,把其中的 httpmime.jar 放進專案即可:

用法是:用 InputStreamBody 包裝檔案串流、用 StringBody 包裝文字欄位,全部塞進 MultipartEntity,再把這個 entity 設為 POST 的請求本文。
服務端則使用 Apache Commons FileUpload 處理,需要 commons-fileupload 與 commons-io 兩個 jar:
public class UploadServlet extends HttpServlet {
@Override
@SuppressWarnings("rawtypes")
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if (isMultipart) {
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
try {
List items = upload.parseRequest(request);
Iterator iter = items.iterator();
while (iter.hasNext()) {
FileItem item = (FileItem) iter.next();
if (item.isFormField()) {
// 純文字欄位
System.out.println(item.getFieldName() + ":" + item.getString());
} else {
// 檔案欄位
String fileName = item.getName();
byte[] data = item.get();
String filePath = getServletContext().getRealPath("/files")
+ "/" + fileName;
FileOutputStream fos = new FileOutputStream(filePath);
fos.write(data);
fos.close();
}
}
} catch (FileUploadException e) {
e.printStackTrace();
}
}
response.getWriter().write("UPLOAD_SUCCESS");
}
}
上面每次都 new 一個 HttpClient 的寫法在實務中不可取。正確做法是整個 App 共用一個 HttpClient 實例,並且注意多執行緒同時發請求時的執行緒安全問題。改良方式有兩步:
改良後的專案結構:

public class MyApplication extends Application {
private HttpClient httpClient;
@Override
public void onCreate() {
super.onCreate();
httpClient = this.createHttpClient();
}
@Override
public void onLowMemory() {
super.onLowMemory();
this.shutdownHttpClient();
}
@Override
public void onTerminate() {
super.onTerminate();
this.shutdownHttpClient();
}
/** 建立具備執行緒安全連線管理器的 HttpClient */
private HttpClient createHttpClient() {
HttpParams params = new BasicHttpParams();
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
HttpProtocolParams.setContentCharset(params, HTTP.DEFAULT_CONTENT_CHARSET);
HttpProtocolParams.setUseExpectContinue(params, true);
SchemeRegistry schReg = new SchemeRegistry();
schReg.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
schReg.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));
ClientConnectionManager connMgr = new ThreadSafeClientConnManager(params, schReg);
return new DefaultHttpClient(connMgr, params);
}
/** 釋放連線資源 */
private void shutdownHttpClient() {
if (httpClient != null && httpClient.getConnectionManager() != null) {
httpClient.getConnectionManager().shutdown();
}
}
public HttpClient getHttpClient() {
return httpClient;
}
}
接著在 Manifest 註冊這個自訂的 Application,否則系統只會用預設的 android.app.Application:
<application android:name=".MyApplication" ...> ... </application>
之後在任何 Context 中都能用 getApplication() 取得實例。實際使用如下:
public class HttpActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button btn = (Button) findViewById(R.id.btn);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
execute();
}
});
}
private void execute() {
new Thread(new Runnable() {
@Override
public void run() {
try {
MyApplication app = (MyApplication) getApplication();
HttpClient client = app.getHttpClient();
HttpGet get = new HttpGet(
"https://192.168.1.57:8080/web/TestServlet?id=1001&name=john&age=60");
HttpResponse response = client.execute(get);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
final String result =
inStream2String(response.getEntity().getContent());
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(HttpActivity.this, result,
Toast.LENGTH_LONG).show();
}
});
}
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}
}
點擊 execute 按鈕後的執行結果:

把自訂 Android 元件打包成 JAR 的實作方法
在專案開發中,難免會需要自己製作自訂 View 控制項。後續其他專案若也需要,多數人的做法是直接複製貼上——這雖然可行,但並不是好解法。 問題在於,隨著專案數量累積,自訂
Android 實現 ViewPager 實時滑動跟手效果的兩種方式
本文介紹如何讓 ViewPager 的滑動效果與指示器實時同步,實現「跟手」的翻頁體驗,並給出兩種常見做法,供大家參考。 先看看效果圖: activity_main.x
Android 刮刮樂效果實作:用 Canvas 與触摸事件模擬橡皮擦
刮刮樂的核心原理刮刮樂效果本質上是「擦除遮罩」。可以用自定義 View 搭配 Bitmap、Canvas 與 Paint,在手指移動時繪出透明路徑,模擬橡皮擦。橡皮擦實作
Android ListView 局部刷新:避免 notifyDataSetChanged 的進度條更新方案
ListView 的刷新機制是 Android 開發中的常見主題。一般做法是在資料變更後呼叫 notifyDataSetChanged,讓 ListView 重新繪製。但