目录

chen 的个人博客

VX:ZzzChChen
Phone:13403656751
Email:zxydczzs@gmail.com

X

Java OkHttp的基本使用

一、pom.xml

 1        <dependency>
 2            <groupId>com.squareup.okhttp3</groupId>
 3            <artifactId>okhttp</artifactId>
 4            <version>4.8.1</version>
 5        </dependency>
 6
 7        <dependency>
 8            <groupId>org.jetbrains.kotlin</groupId>
 9            <artifactId>kotlin-stdlib</artifactId>
10            <version>1.3.70</version>
11        </dependency>

二、GET 请求

1、普通 get 请求。

 1        OkHttpClient client = new OkHttpClient();
 2        Request request = new Request.Builder()
 3                .url(url)
 4                .build();
 5        try {
 6            Response response = client.newCall(request).execute();
 7            System.out.println(response.body().string());
 8        } catch (IOException e) {
 9	    e.printStackTrace();
10        }

2、添加请求头参数

 1        OkHttpClient client = new OkHttpClient();
 2        Request request = new Request.Builder()
 3                .url(url)
 4                .addHeader("client_id", "123")
 5                .addHeader("sign", "123")
 6                .addHeader("sign_method", "123")
 7                .addHeader("t", "123")
 8                .build();
 9        try {
10            Response response = client.newCall(request).execute();
11            System.out.println(response.body().string());
12        } catch (IOException e) {
13	e.printStackTrace();
14        }

三、POST 请求

1、表单 POST 请求

 1        OkHttpClient client = new OkHttpClient();
 2
 3        // 提交FormData
 4        FormBody.Builder form = new FormBody.Builder();
 5        form.add("name", "Tom");
 6        form.add("age", "23");
 7
 8        Request request = new Request.Builder()
 9                .url("http://httpbin.org/post")
10                .post(form.build())
11                .build();
12
13        Response response = client.newCall(request).execute();
14        System.out.println(response.body().string());

2、JSON 提交

 1        public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
 2
 3        OkHttpClient client = new OkHttpClient();
 4
 5        Map<String, Object> map = new HashMap<>();
 6        map.put("name", "Tom");
 7        map.put("age", 23);
 8
 9        Gson gson = new Gson();
10        String data = gson.toJson(map);
11
12        RequestBody requestBody = RequestBody.create(data, JSON);
13
14        Request request = new Request.Builder()
15                .url("http://httpbin.org/post")
16                .post(requestBody)
17                .build();
18
19        Response response = client.newCall(request).execute();
20        System.out.println(response.body().string()); 

已在真实项目中运行。

参考 demo:

https://blog.csdn.net/mouday/article/details/108253164

https://www.cnblogs.com/lxlw/p/11767888.html


标题:Java OkHttp的基本使用
作者:zzzzchen
地址:https://dczzs.com/articles/2021/06/03/1622716479297.html