当前位置:   article > 正文

SpringBoot 整合okHttp3 okhttp3用法 okhttp整合 okhttp用法 SpringBoot 整合okHttp3_okhttp3 maven

okhttp3 maven

1、引入Maven依赖

        <!--okhttp3 依赖-->
        <dependency>
            <groupId>com.squareup.okhttp3</groupId>
            <artifactId>okhttp</artifactId>
            <version>4.9.3</version>
        </dependency>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

2、发起请求 (同步)

2.1、GET请求

OkHttpClient client = new OkHttpClient();

Request request = new Request.Builder()
        .url("http://www.example.com/api/resource?q=123123")
        .header("token", "qweqweasd123123123")
        .build();

try {
    Response response = client.newCall(request).execute();
    
    if (response.isSuccessful()) {
        String responseBody = response.body().string();
        System.out.println(responseBody);
    } else {
        System.out.println("请求失败,错误码:" + response.code());
    }
} catch (IOException e) {
    e.printStackTrace();
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19

GET 请求需要传递 application/json参数

       OkHttpClient client = new OkHttpClient();

        MediaType mediaType = MediaType.parse("application/json");
        String jsonBody = "{\"key\": \"value\"}";

        // 创建请求体
        RequestBody requestBody = RequestBody.create(jsonBody, mediaType);

        // 创建GET请求并携带请求体
        Request request = new Request.Builder()
                .url("http://example.com/api/endpoint")
                .get()
                .header("Content-Type", "application/json")
                .method("GET", requestBody)
                .build();

        try {
            // 发送请求并获取响应
            Response response = client.newCall(request).execute();
            // 处理响应...
        } catch (IOException e) {
            e.printStackTrace();
        }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23

2.2、POST请求

String jsonData = "{\"name\": \"lizr\"}";
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
        .url("http://www.example.com/api/resource")
        .post(RequestBody.create(jsonData.getBytes(), MediaType.parse("application/json")))
        .header("token", "qweqweasd123123123")
        .build();

try {
    Response response = client.newCall(request).execute();
    
    if (response.isSuccessful()) {
        String responseBody = response.body().string();
        System.out.println(responseBody);
    } else {
        System.out.println("请求失败,错误码:" + response.code());
    }
} catch (IOException e) {
    e.printStackTrace();
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20

2.3、PUT请求

String jsonData = "{\"name\": \"lizr\"}";
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
        .url("http://www.example.com/api/resource")
        .put(RequestBody.create(jsonData.getBytes(), MediaType.parse("application/json")))
        .header("token", "qweqweasd123123123")
        .build();

try {
    Response response = client.newCall(request).execute();
    
    if (response.isSuccessful()) {
        String responseBody = response.body().string();
        System.out.println(responseBody);
    } else {
        System.out.println("请求失败,错误码:" + response.code());
    }
} catch (IOException e) {
    e.printStackTrace();
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20

2.4、DELETE请求

String jsonData = "{\"name\": \"lizr\"}";
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
        .url("http://www.example.com/api/resource")
        .delete(RequestBody.create(jsonData.getBytes(), MediaType.parse("application/json")))
        .header("token", "qweqweasd123123123")
        .build();

try {
    Response response = client.newCall(request).execute();
    
    if (response.isSuccessful()) {
        String responseBody = response.body().string();
        System.out.println(responseBody);
    } else {
        System.out.println("请求失败,错误码:" + response.code());
    }
} catch (IOException e) {
    e.printStackTrace();
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20

3、发起请求 (异步)

3.1、GET请求

OkHttpClient client = new OkHttpClient();

String url = "https://example.com/api/user";

Request request = new Request.Builder()
        .url(url)
        .header("token", "qweqweasd123123123")
        .build();

client.newCall(request).enqueue(new Callback() {
    @Override
    public void onResponse(Call call, Response response) throws IOException {
        // 处理响应数据
        String responseBody = response.body().string();
        System.out.println(responseBody);
    }

    @Override
    public void onFailure(Call call, IOException e) {
        // 处理请求失败情况
        e.printStackTrace();
    }
});
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23

3.2、POST请求

OkHttpClient client = new OkHttpClient();

String url = "https://example.com/api/user";
MediaType mediaType = MediaType.parse("application/json; charset=utf-8");
String requestBody = "{\"username\":\"john\", \"password\":\"123456\"}";


RequestBody body = RequestBody.create(mediaType, requestBody);

Request request = new Request.Builder()
        .url(url)
        .post(body)
        .header("token", "qweqweasd123123123")
        .build();

client.newCall(request).enqueue(new Callback() {
    @Override
    public void onResponse(Call call, Response response) throws IOException {
        // 处理响应数据
        String responseBody = response.body().string();
        System.out.println(responseBody);
    }

    @Override
    public void onFailure(Call call, IOException e) {
        // 处理请求失败情况
        e.printStackTrace();
    }
});
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29

3.3、PUT请求

OkHttpClient client = new OkHttpClient();

String url = "https://example.com/api/user";
MediaType mediaType = MediaType.parse("application/json; charset=utf-8");
String requestBody = "{\"username\":\"john\", \"password\":\"123456\"}";


RequestBody body = RequestBody.create(mediaType, requestBody);

Request request = new Request.Builder()
        .url(url)
        .put(body)
        .header("token", "qweqweasd123123123")
        .build();

client.newCall(request).enqueue(new Callback() {
    @Override
    public void onResponse(Call call, Response response) throws IOException {
        // 处理响应数据
        String responseBody = response.body().string();
        System.out.println(responseBody);
    }

    @Override
    public void onFailure(Call call, IOException e) {
        // 处理请求失败情况
        e.printStackTrace();
    }
});
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29

3.4、DELETE请求

OkHttpClient client = new OkHttpClient();

String url = "https://example.com/api/user";
MediaType mediaType = MediaType.parse("application/json; charset=utf-8");
String requestBody = "{\"username\":\"john\", \"password\":\"123456\"}";


RequestBody body = RequestBody.create(mediaType, requestBody);

Request request = new Request.Builder()
        .url(url)
        .delete(body)
        .header("token", "qweqweasd123123123")
        .build();

client.newCall(request).enqueue(new Callback() {
    @Override
    public void onResponse(Call call, Response response) throws IOException {
        // 处理响应数据
        String responseBody = response.body().string();
        System.out.println(responseBody);
    }

    @Override
    public void onFailure(Call call, IOException e) {
        // 处理请求失败情况
        e.printStackTrace();
    }
});
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29

4、连接池

可以使用连接池来管理和复用HTTP和HTTPS连接,以提高性能和效率

// 创建连接池对象
ConnectionPool connectionPool = new ConnectionPool(5, 10, TimeUnit.MINUTES);

// 创建OkHttpClient并设置连接池
OkHttpClient client = new OkHttpClient.Builder()
        .connectionPool(connectionPool)
        .build();

// 创建请求对象
Request request = new Request.Builder()
        .url("http://www.example.com")
        .build();

try {
    // 发送请求并获取响应
    Response response = client.newCall(request).execute();

    if (response.isSuccessful()) {
        String responseBody = response.body().string();
        System.out.println(responseBody);
    } else {
        System.out.println("请求失败,错误码:" + response.code());
    }
} catch (IOException e) {
    e.printStackTrace();
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26

上述代码中,通过创建ConnectionPool对象,并将其设置到OkHttpClient中,从而启用了连接池功能。ConnectionPool的构造函数接受三个参数:maxIdleConnections、keepAliveDuration和timeUnit,用于配置连接池的最大空闲连接数、连接保持时间以及时间单位。

连接池会自动管理和复用连接,适当地回收和关闭空闲的连接。这样可以避免频繁地创建和关闭连接,提高性能和效率,特别是在多次请求同一主机时。

合理地设置连接池参数非常重要,以符合你的实际需求。可以根据并发请求的数量、目标服务器的负载能力以及网络环境等因素来调整连接池的大小和保持时间。

有关更多详细信息和高级用法,建议参考 okhttp3 的官方文档或其他相关资料。

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/article/detail/45648
推荐阅读
相关标签
  

闽ICP备14008679号