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

Android 網路請求實戰:JSON POST、HTTP 與 HTTPS 憑證處理

編輯:關於 Android 程式設計

Android 上發網路請求的方式很多,但真正與後端對接時,需要處理的細節比想像中多:編碼、超時、自訂 Header、重試,以及 HTTPS 的憑證驗證。這裡把自己專案裡用的三段程式碼整理出來。

一、以 JSON 為 body 的 POST 請求

Android SDK 已經把 JSON 相關操作封裝得很好,組 body 很直覺。

/**
 * 發送 JSON 格式的 HTTP 請求
 * @return 回應的 HTTP 狀態碼
 */
@SuppressLint("DefaultLocale")
public int httpResponseCodeJsonPost(String strUrl, String authorization,
        String currentSessionId, String ClientId,
        PostParameter[] postParams, String httpMethod) throws SystemException {

    int responseCode = -1;
    try {
        HttpPost request = new HttpPost(strUrl);
        JSONObject param = new JSONObject();

        for (int j = 0; j < postParams.length; j++) {
            param.put(postParams[j].name, postParams[j].value);
        }

        try {
            // 指定 UTF-8,避免中文參數變亂碼
            StringEntity se = new StringEntity(param.toString(), "utf-8");
            request.setEntity(se);
        } catch (UnsupportedEncodingException e1) {
            e1.printStackTrace();
        }

        // 連線與讀取超時(毫秒)
        request.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 5000);
        request.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 5000);

        // 自訂請求頭
        request.setHeader("X-FBox-Session", currentSessionId);
        request.setHeader("Authorization", authorization);
        request.setHeader("X-FBox-ClientId", ClientId);
        request.setHeader("Content-Type", "application/json;charset=UTF-8");

        try {
            HttpResponse httpResponse = new DefaultHttpClient().execute(request);
            // String retSrc = EntityUtils.toString(httpResponse.getEntity());  // 回應內容
            responseCode = httpResponse.getStatusLine().getStatusCode();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }
    return responseCode;
}

二、一般的 application/x-www-form-urlencoded 請求

這版改用 HttpURLConnection,並加入了重試機制。

@SuppressLint("DefaultLocale")
public int httpResponseCode(String strUrl, String authorization,
        String currentSessionId, String ClientId,
        PostParameter[] postParams, String httpMethod) throws SystemException {

    int retry = 1;
    Response res = null;
    int responseCode = -1;

    for (int retriedCount = 0; retriedCount < retry; retriedCount++) {
        HttpURLConnection con = null;
        OutputStream osw = null;
        try {
            URL url = new URL(strUrl);
            con = (HttpURLConnection) url.openConnection();
            con.setDoInput(true);
            con.setRequestProperty("Authorization", authorization);
            con.addRequestProperty("X-FBox-ClientId", ClientId);
            setHeaders(strUrl, postParams, con, httpMethod);

            if ("POST".equals(httpMethod) || "PUT".equals(httpMethod)) {
                con.setRequestMethod(httpMethod);
                con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                con.setDoOutput(true);

                String postParam = "";
                if (postParams != null) {
                    postParam = encodeParameters(postParams);
                }
                byte[] bytes = postParam.getBytes("UTF-8");
                con.setRequestProperty("Content-Length", Integer.toString(bytes.length));

                osw = con.getOutputStream();
                osw.write(bytes);
                osw.flush();
                osw.close();
            } else {
                con.setRequestMethod(httpMethod);
            }

            con.setConnectTimeout(this.connectionTimeout);
            con.setReadTimeout(this.readTimeout);

            res = new Response(con);
            responseCode = con.getResponseCode();
        } finally {
            if (osw != null) {
                try { osw.close(); } catch (Exception ignore) { }
            }
        }
        // 攔截逾時並依重試次數決定是否拋出
        catch (IOException ioe) {
            if (retriedCount == 1) {
                throw new SystemException(ioe.getMessage(), ioe, responseCode);
            }
        }
    }
    return responseCode;
}

三、加上 HTTPS 支援

若 URL 是 https,需要多兩步:換成 HttpsURLConnection,並決定如何處理憑證。

if (url.getProtocol().toLowerCase().equals("https")) {
    trustAllHosts();                                    // 信任所有憑證(僅供開發/測試)
    HttpsURLConnection https = (HttpsURLConnection) url.openConnection();
    https.setHostnameVerifier(DO_NOT_VERIFY);
    con = https;
} else {
    con = (HttpURLConnection) url.openConnection();
}

配套的信任管理器:

/**
 * 信任所有主機——對任何憑證都不做檢查
 * Android 採用 X.509 憑證機制
 */
@SuppressLint("TrulyRandom")
private static void trustAllHosts() {
    // 建立一個不驗證憑證鏈的信任管理器
    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return new java.security.cert.X509Certificate[] {};
        }

        public void checkClientTrusted(X509Certificate[] chain, String authType)
                throws CertificateException { }

        public void checkServerTrusted(X509Certificate[] chain, String authType)
                throws CertificateException { }
    } };

    try {
        SSLContext sc = SSLContext.getInstance("TLS");
        sc.init(null, trustAllCerts, new java.security.SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
    } catch (Exception e) {
        e.printStackTrace();
    }
}

四、關於 trustAllHosts 的必要警告

上面這段程式碼在網路上到處可見,但它關掉了 HTTPS 的全部保護。使用它,等於允許任何中間人冒充你的伺服器、讀取並竄改所有傳輸內容。它能存在的原因只有一個:讓開發階段可以先用自簽憑證的測試環境跑通。

正式產品請改用以下任一方案:

  • 使用正規 CA 簽發的憑證:什麼都不用做,預設就會通過驗證。這是 99% 情況的正解。
  • 憑證鎖定(Certificate Pinning):把伺服器憑證或公鑰的摘要寫死在 App 裡,連系統信任的 CA 也無法偽造。OkHttp 的 CertificatePinner 支援這個功能。
  • 信任自簽憑證:把你的憑證放進 res/raw,用 KeyStore 載入後組 SSLContext,只信任這一個憑證,而非全部。

五、幾個實務建議

  • 別在主線程發請求:NetworkOnMainThreadException 從 API 11 就開始拋了,請用 Thread/AsyncTask/OkHttp 的非同步介面。
  • Apache HttpClient 已被移除:DefaultHttpClient 與 HttpPost 在 API 23 起被從 SDK 中刪除,新專案請直接用 HttpURLConnection 或 OkHttp。
  • 超時一定要設:預設值在某些裝置上是無限等待,弱網環境下會讓使用者盯著轉圈石頭十幾秒。
  • 重試要有上限與退避:上面範例的 retry = 1 其實只跑一次,等於沒重試。實務上建議 2~3 次並搭配指數退避,且只對「連線失敗」重試,4xx 錯誤重試沒有意義。
  • 回應要關流:EntityUtils.toString() 之後記得 consume() 或關閉 entity,否則連線無法被連線池複用,會造成 socket 耗盡。
  • 建議直接上 OkHttp:它自帶連線池、攔截器鏈、GZIP、HTTP/2、憑證鎖定與成熟的重試策略,上面三段程式碼要自己處理的問題它都處理好了。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved