Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 中的 HTTP 通訊實戰:用 HttpClient 完成 GET、POST 與檔案上傳

編輯:關於 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 指的是模擬器自己,顯然找不到服務。

案例一:GET 的服務端

參數直接附加在網址後面,由 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 的服務端

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");
    }
}

進階:全域共用一個 HttpClient

上面每次都 new 一個 HttpClient 的寫法在實務中不可取。正確做法是整個 App 共用一個 HttpClient 實例,並且注意多執行緒同時發請求時的執行緒安全問題。改良方式有兩步:

  1. 擴充系統的 Application,把 HttpClient 的生命週期綁在 App 上。
  2. 用 ThreadSafeClientConnManager 建立連線管理器,讓 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 按鈕後的執行結果:

重點回顧

  • 權限優先:沒有 INTERNET 權限,什麼都連不上。
  • 用 IP 而非 localhost:模擬器與本機是兩個不同的環境。
  • 執行緒規則:網路請求絕對不能放在主執行緒(Android 4.0 起會直接拋 NetworkOnMainThreadException),UI 更新也必須回到主執行緒。
  • 單例 HttpClient:全域共用一個實例,並以 ThreadSafeClientConnManager 確保併發安全。
  • 現今替代方案:Apache HttpClient 已在 Android 5.0 之後被移除,新專案請改用 HttpURLConnection 或 OkHttp/Retrofit。本文的觀念(連線重用、執行緒切換、multipart 上傳流程)依然適用。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved