使用OkHttp发送POST请求的几种方式

使用OkHttp发送POST请求的几种方式

    • 介绍
    • pom依赖
    • 基本的POST请求
    • 带授权的POST请求
    • POST方式发送JSON数据
    • Multipart POST 请求

介绍

本文将介绍 OkHttp 客户端的基本用法。
主要介绍 OkHttp 3.x 版本中发送Post请求的几种方式。

pom依赖

        <dependency>
            <groupId>com.squareup.okhttp3</groupId>
            <artifactId>okhttp</artifactId>
            <version>4.8.0</version>
        </dependency>

基本的POST请求

使用 FormBody.Builder 构造基本的 RequestBody , 包含两个参数:用户名、密码,发送 POST请求。

    public static void main(String[] args) {
        String BASE_URL = "http://localhost:8080/okhttp3/test";

        RequestBody formBody = new FormBody.Builder()
                .add("username", "zhangsan")
                .add("password", "123456")
                .build();

        Request request = new Request.Builder()
                .url(BASE_URL + "/users")
                .post(formBody)
                .build();

        Call call = new OkHttpClient().newCall(request);
        Response response = null;
        try {
            response = call.execute();
        } catch (IOException e) {
            System.out.println("execute failed, message:" + e.getMessage());
        }

        assert response != null;
        if (!response.isSuccessful()) {
            System.out.println("request failed");
        }
    }

带授权的POST请求

如果要对请求进行身份验证,可以使用 Credentials.basic 构建器向请求头中添加凭据。
下面代码给出发送一个 String 字符串作为请求体带授权的例子:

    public static void main(String[] args) {
        String BASE_URL = "http://localhost:8080/okhttp3/test";

        // 带授权的POST请求
        String postBody = "content";

        Request request = new Request.Builder()
                .url(BASE_URL + "/users")
                .addHeader("Authorization", Credentials.basic("username", "password"))
                .post(RequestBody.create(MediaType.parse("text/x-markdown"), postBody)).build();


        Call call = new OkHttpClient().newCall(request);
        Response response = null;
        try {
            response = call.execute();
        } catch (IOException e) {
            System.out.println("execute failed, message:" + e.getMessage());
        }

        assert response != null;
        if (!response.isSuccessful()) {
            System.out.println("request failed");
        }
    }

POST方式发送JSON数据

为了在请求体中发送 JSON,我们必须设置它的媒体类型 application/json。 我们可以使用 RequestBody.create构建器来构造:

    public static void main(String[] args) {
        String BASE_URL = "http://localhost:8080/okhttp3/test";

        // POST方式发送JSON数据
        String json = "{\"username\":zhangsan,\"password\":\"123456\"}";
        RequestBody body = RequestBody.create(MediaType.parse("application/json"), json);

        Request request = new Request.Builder()
                .url(BASE_URL + "/users")
                .post(body)
                .build();

        Call call = new OkHttpClient().newCall(request);
        Response response = null;
        try {
            response = call.execute();
        } catch (IOException e) {
            System.out.println("execute failed, message:" + e.getMessage());
        }

        assert response != null;
        if (!response.isSuccessful()) {
            System.out.println("request failed");
        }
    }

Multipart POST 请求

我们需要将 RequestBody 构建为一个 MultipartBody 来发布文件、用户名和密码的 POST 请求:

    public static void main(String[] args) {
        String BASE_URL = "http://localhost:8080/okhttp3/test";

        // Multipart POST请求
        RequestBody requestBody = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("username", "zhangsan")
                .addFormDataPart("password", "123456")
                .addFormDataPart("file", "file.txt",
                        RequestBody.create(MediaType.parse("application/octet-stream"), 
                                new File("src/test/resources/test.txt")))
                .build();

        Request request = new Request.Builder()
                .url(BASE_URL + "/users/multipart")
                .post(requestBody)
                .build();

        Call call = new OkHttpClient().newCall(request);
        Response response = null;
        try {
            response = call.execute();
        } catch (IOException e) {
            System.out.println("execute failed, message:" + e.getMessage());
        }

        assert response != null;
        if (!response.isSuccessful()) {
            System.out.println("request failed");
        }
    }

你可能感兴趣的:(网络/协议,okhttp,https,java)