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

OkHttp 發送 POST 請求的五種方式詳解

編輯:關於 Android 程式設計

HTTP POST 與 PUT 請求可以攜帶要提交的內容。在 OkHttp 中,只需在建立 Request 物件時透過 post() 或 put() 指定內容即可。本文依「字串、串流、檔案、表單、多部件」五種情境,示範各自的寫法。

一、以字串提交(適合小量內容)

public class PostString {
    public static void main(String[] args) throws IOException {
        OkHttpClient client = new OkHttpClient();
        MediaType MEDIA_TYPE_TEXT = MediaType.parse("text/plain");

        String postBody = "Hello World";
        Request request = new Request.Builder()
                .url("https://www.baidu.com")
                .post(RequestBody.create(MEDIA_TYPE_TEXT, postBody))
                .build();

        Response response = client.newCall(request).execute();
        if (!response.isSuccessful()) {
            throw new IOException("服務器端錯誤: " + response);
        }
        System.out.println(response.body().string());
    }
}

以 String 提交只適用於內容較小的情況。當請求內容龐大時,應改用串流方式,避免一次性把整份資料載入記憶體。

二、以串流提交

請求體的內容由串流寫入產生。以下範例直接寫入 Okio 的 BufferedSink;若你的程式使用 OutputStream,可透過 BufferedSink.outputStream() 取得。

public static final MediaType MEDIA_TYPE_MARKDOWN =
        MediaType.parse("text/x-markdown; charset=utf-8");

private final OkHttpClient client = new OkHttpClient();

public void run() throws Exception {
    RequestBody requestBody = new RequestBody() {
        @Override
        public MediaType contentType() {
            return MEDIA_TYPE_MARKDOWN;
        }

        @Override
        public void writeTo(BufferedSink sink) throws IOException {
            sink.writeUtf8("Numbers\n");
            sink.writeUtf8("-------\n");
            for (int i = 2; i <= 997; i++) {
                sink.writeUtf8(String.format(" * %s = %s\n", i, factor(i)));
            }
        }

        private String factor(int n) {
            for (int i = 2; i < n; i++) {
                int x = n / i;
                if (x * i == n) return factor(x) + " × " + i;
            }
            return Integer.toString(n);
        }
    };

    Request request = new Request.Builder()
            .url("https://api.github.com/markdown/raw")
            .post(requestBody)
            .build();

    Response response = client.newCall(request).execute();
    if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
    System.out.println(response.body().string());
}

三、以檔案提交

把檔案作為請求體非常簡單,RequestBody.create 直接接受 File 物件:

public static final MediaType MEDIA_TYPE_MARKDOWN =
        MediaType.parse("text/x-markdown; charset=utf-8");

private final OkHttpClient client = new OkHttpClient();

public void run() throws Exception {
    File file = new File("README.md");

    Request request = new Request.Builder()
            .url("https://api.github.com/markdown/raw")
            .post(RequestBody.create(MEDIA_TYPE_MARKDOWN, file))
            .build();

    Response response = client.newCall(request).execute();
    if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
    System.out.println(response.body().string());
}

四、以表單提交

使用 FormEncodingBuilder 可建構出與 HTML <form> 相同效果的請求體,鍵值對會以 HTML 相容的 URL 編碼方式處理:

private final OkHttpClient client = new OkHttpClient();

public void run() throws Exception {
    RequestBody formBody = new FormEncodingBuilder()
            .add("search", "Jurassic Park")
            .build();

    Request request = new Request.Builder()
            .url("https://en.wikipedia.org/w/index.php")
            .post(formBody)
            .build();

    Response response = client.newCall(request).execute();
    if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
    System.out.println(response.body().string());
}

五、以多部件(multipart)提交

MultipartBuilder 可建構複雜的請求體,與 HTML 的檔案上傳格式相容。多部件請求體中每一部分都是獨立的請求體,可定義自己的標頭;這些標頭用來描述該部分內容,例如它的 Content-Disposition。若 Content-Length 與 Content-Type 可用,會被自動加入標頭。

private static final String IMGUR_CLIENT_ID = "...";
private static final MediaType MEDIA_TYPE_PNG = MediaType.parse("image/png");

private final OkHttpClient client = new OkHttpClient();

public void run() throws Exception {
    // 使用 imgur 的圖片上傳 API
    RequestBody requestBody = new MultipartBuilder()
            .type(MultipartBuilder.FORM)
            .addPart(
                    Headers.of("Content-Disposition", "form-data; name=\"title\""),
                    RequestBody.create(null, "Square Logo"))
            .addPart(
                    Headers.of("Content-Disposition", "form-data; name=\"image\""),
                    RequestBody.create(MEDIA_TYPE_PNG, new File("website/static/logo-square.png")))
            .build();

    Request request = new Request.Builder()
            .header("Authorization", "Client-ID " + IMGUR_CLIENT_ID)
            .url("https://api.imgur.com/3/image")
            .post(requestBody)
            .build();

    Response response = client.newCall(request).execute();
    if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
    System.out.println(response.body().string());
}

版本差異提醒

本文範例基於 OkHttp 3.x 的 API 寫法。在 OkHttp 4.x 中,由於改用 Kotlin 撰寫,部分 Builder 類別(如 FormEncodingBuilder、MultipartBuilder)已被 FormBody.Builder 與 MultipartBody.Builder 取代,RequestBody.create 的參數順序也有所調整。若使用新版,請以對應的 Builder 寫法為準。此外,記得在執行網路請求前於 AndroidManifest.xml 加上 android.permission.INTERNET 權限,並避免在主執行緒執行同步請求。

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