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

Android 以 Apache HttpClient 送出 POST 請求的完整封裝

編輯:關於 Android 程式設計

早期 Android 內建 Apache HttpClient,是送出表單式 POST 請求最直覺的選擇。以下封裝成一個工具類,輸入 Map、編碼與網址,直接回傳回應字串。

package com.liuc;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;

public class HttpPostUtil {

    public static String sendHttpPost(Map<String, String> map, String encode, String path) {

        // 1. 把 Map 攤平成 NameValuePair 清單
        List<NameValuePair> list = new ArrayList<NameValuePair>();
        if (map != null && !map.isEmpty()) {
            for (Map.Entry<String, String> entry : map.entrySet()) {
                list.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
            }
        }

        try {
            // 2. 封裝成表單實體,也就是請求主體
            UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, encode);

            HttpPost httpPost = new HttpPost(path);
            httpPost.setEntity(entity);

            // 3. 設定逾時(4.3 之後改用 RequestConfig)
            RequestConfig requestConfig = RequestConfig.custom()
                    .setSocketTimeout(2000)
                    .setConnectTimeout(2000)
                    .build();
            httpPost.setConfig(requestConfig);

            // 4. 執行請求
            // 3.x 的寫法是 new DefaultHttpClient(),4.x 之後改用 HttpClients.createDefault()
            HttpClient httpClient = HttpClients.createDefault();
            HttpResponse httpResponse = httpClient.execute(httpPost);

            if (httpResponse.getStatusLine().getStatusCode() == 200) {
                return getStringForInputStream(httpResponse.getEntity().getContent(), encode);
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return path;
    }

    /** 把串流讀成字串,需自行關閉 */
    private static String getStringForInputStream(InputStream inputStream, String encode) {
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        byte[] data = new byte[1024];
        int len = 0;
        String result = "";
        try {
            if (inputStream != null) {
                while ((len = inputStream.read(data)) != -1) {
                    stream.write(data, 0, len);
                }
                result = new String(stream.toByteArray(), encode);
            }
        } catch (Exception e) {
            // 實務上請至少記錄 log,不要靜默吞掉
        }
        return result;
    }
}

呼叫方式

Map<String, String> params = new HashMap<String, String>();
params.put("username", "test");
params.put("page", "1");

String result = HttpPostUtil.sendHttpPost(params, "UTF-8", "https://example.com/api/login");

幾個必須知道的現實問題

  • 不能放在主執行緒:Android 4.0 之後網路請求若發生在主執行緒會直接拋 NetworkOnMainThreadException。請用 AsyncTask、執行緒池或(更推薦的)OkHttp/Retrofit 搭配非同步回呼。
  • HttpClient 已被官方淘汰:Android 5.0 起 org.apache.http 被標記為 uses-library 需顯式宣告,Android 6.0 更直接從 SDK 移除,必須自行打包 useLibrary 'org.apache.http.legacy' 或引入 jar。新專案請改用 HttpURLConnection 或 OkHttp。
  • 這個封裝的幾個瑕疵:回傳失敗時傳回 path(也就是把網址當結果回傳)是很危險的設計,呼叫端容易誤判成功;例外被靜默吞掉也讓除錯變成惡夢。建議改成拋出自訂例外或回傳帶狀態的結果物件。
  • 一定要關串流:InputStream 未關閉會造成連線無法回收。若仍使用 HttpClient,建議用 EntityUtils.toString(entity, encode) 取代手寫讀取,它會妥善處理資源。
  • 字元編碼要一致:請求端與回應端編碼不同會出現亂碼。若伺服器回傳的 Content-Type 標頭含 charset,應優先採用該值。
  • 記得權限:<uses-permission android:name="android.permission.INTERNET" />,缺少時一樣是一片空白。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved