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

使用 HttpClient 框架發送 POST 請求

編輯:關於 Android 程式設計

Apache HttpClient 的 POST 寫法比 GET 更直觀:把要送出的欄位放進一個 List<NameValuePair>,包裝成 UrlEncodedFormEntity 掛到 HttpPost 上即可,不必自己拼字串。

/**
 * 以 HttpClient 的 POST 方式發送請求
 *
 * @param username 使用者名稱
 * @param password 密碼
 * @return null 表示請求路徑有問題,text 為請求取得的資料
 */
public static String httpclientPost(String username, String password) {
    try {
        // 1. 建立客戶端
        HttpClient client = new DefaultHttpClient();

        // 2. 指定請求位址與方式
        String path = "https://172.22.64.156:8080/0001AndroidWebService/LoginServlet";
        HttpPost post = new HttpPost(path);

        // 準備要提交的資料實體
        List<NameValuePair> parameters = new ArrayList<NameValuePair>();
        parameters.add(new BasicNameValuePair("username", username));
        parameters.add(new BasicNameValuePair("password", password));
        post.setEntity(new UrlEncodedFormEntity(parameters, "UTF-8"));

        // 3. 送出請求
        HttpResponse response = client.execute(post);

        // 取得回應狀態碼
        int code = response.getStatusLine().getStatusCode();
        if (code == 200) {
            InputStream is = response.getEntity().getContent();
            String text = StreamUtil.readStream(is);
            return text;
        } else {
            return null;
        }
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}

為什麼這個寫法比較省心

用 NameValuePair 清單組裝參數,等於把編碼工作交給 UrlEncodedFormEntity 處理,中文與特殊字元不會出問題,也不必自己算 Content-Length。這正好避開了手寫 HttpURLConnection POST 時最常見的兩個坑。

版本相容性提醒

同樣地,Apache HttpClient 自 Android 6.0(API 23)起已被移出平台。若要在新專案沿用,需於 Gradle 中加入:

android {
    useLibrary 'org.apache.http.legacy'
}

或改用 OkHttp,它提供了幾乎等價的表單提交能力:

OkHttpClient client = new OkHttpClient();
RequestBody body = new FormBody.Builder()
        .add("username", username)
        .add("password", password)
        .build();
Request request = new Request.Builder()
        .url(path)
        .post(body)
        .build();
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved