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

Android POST 請求實作:JSON 與 Map 兩種資料傳遞方式完整解析

編輯:關於 Android 開發

Android POST 請求實作:JSON 與 Map 兩種資料傳遞方式完整解析

在 Android 開發中,與伺服器互動時經常需要以 POST 方式送出資料。最常見的兩種格式分別是 JSON 與 Map(表單鍵值對),本文將透過 HttpURLConnection 示範這兩種做法,並附上可直接參考的程式碼。

一、以 JSON 格式送出資料

當後端介面要求 Content-Type 為 application/json 時,我們需要把字串形式的 JSON 直接寫入輸出串流。以下程式碼展示了完整的請求流程,包含設定連線逾時、請求方法、寫入資料以及讀取回應:

public static String httpPost(String url, String json) {
    try {
        URL u = new URL(url);
        HttpURLConnection httpURLConnection = (HttpURLConnection) u.openConnection();
        httpURLConnection.setConnectTimeout(TIMEOUT);
        httpURLConnection.setDoInput(true);
        httpURLConnection.setDoOutput(true);
        httpURLConnection.setRequestMethod("POST");
        httpURLConnection.setUseCaches(false);
        httpURLConnection.setRequestProperty("Content-Type", "application/json");
        httpURLConnection.setRequestProperty("Content-Length",
                String.valueOf(json.getBytes().length));
        OutputStream outputStream = httpURLConnection.getOutputStream();
        outputStream.write(json.getBytes());

        int response = httpURLConnection.getResponseCode();
        if (response == HttpURLConnection.HTTP_OK) {
            InputStream inptStream = httpURLConnection.getInputStream();
            return dealResponseResult(inptStream);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return "";
}

而讀取回應資料的部分,可以獨立封裝成一個方法,透過位元組陣列逐段讀取串流,最後轉換為字串:

private static String dealResponseResult(InputStream inputStream) {
    String resultData = null;
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    byte[] data = new byte[1024];
    int len = 0;
    try {
        while ((len = inputStream.read(data)) != -1) {
            byteArrayOutputStream.write(data, 0, len);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    resultData = new String(byteArrayOutputStream.toByteArray());
    return resultData;
}

二、以 Map 格式送出資料

如果傳送的並非 JSON,而是鍵值對形式的 Map,則應改用 application/x-www-form-urlencoded 的表單格式。這時需要先把 Map 拼接成 key=value&key=value 的字串,並對值進行 URL 編碼:

public static String httpPost(String url, Map<String, String> params) {
    byte[] data = getRequestData(params, "utf-8").toString().getBytes();
    try {
        URL u = new URL(url);
        HttpURLConnection httpURLConnection = (HttpURLConnection) u.openConnection();
        httpURLConnection.setConnectTimeout(TIMEOUT);
        httpURLConnection.setDoInput(true);
        httpURLConnection.setDoOutput(true);
        httpURLConnection.setRequestMethod("POST");
        httpURLConnection.setUseCaches(false);
        httpURLConnection.setRequestProperty("Content-Type",
                "application/x-www-form-urlencoded");
        httpURLConnection.setRequestProperty("Content-Length",
                String.valueOf(data.length));
        OutputStream outputStream = httpURLConnection.getOutputStream();
        outputStream.write(data);

        int response = httpURLConnection.getResponseCode();
        if (response == HttpURLConnection.HTTP_OK) {
            InputStream inptStream = httpURLConnection.getInputStream();
            return dealResponseResult(inptStream);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return "";
}

負責拼接表單資料的輔助方法如下,它會遍歷 Map 的每一筆資料,並移除最後多餘的 & 符號:

private static StringBuffer getRequestData(Map<String, String> params, String encode) {
    StringBuffer stringBuffer = new StringBuffer();
    try {
        for (Map.Entry<String, String> entry : params.entrySet()) {
            stringBuffer.append(entry.getKey())
                    .append("=")
                    .append(URLEncoder.encode(entry.getValue(), encode))
                    .append("&");
        }
        stringBuffer.deleteCharAt(stringBuffer.length() - 1); // 移除最後一個 "&"
    } catch (Exception e) {
        e.printStackTrace();
    }
    return stringBuffer;
}

小結:選擇哪一種取決於後端介面的規格。JSON 適合結構化、巢狀的資料,而 Map 表單則適合簡單的鍵值對,兩者在實作上的差異主要在於 Content-Type 與資料的編碼方式。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved