使用OkHttp发送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");
        }
    }
  • 2
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

技术杠精

你的鼓励是我创作最大的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值