okHttp3连接池简单使用

本文介绍了OkHttp3的基本概念,包括其优势,如HTTP/2支持、连接池、透明GZIP等。接着,文章详细阐述了如何简单使用OkHttp3,包括导入jar包、创建单例OkHttpClient、构建请求以及发起同步和异步请求的步骤。提供了相关参考链接以供深入学习。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、概述:

HTTP是现代应用网络的方式。这就是我们交换数据和媒体的方式。有效地执行HTTP可以加快您的负载并节省带宽。

OkHttp是一个默认有效的HTTP客户端:

  • HTTP / 2支持允许对同一主机的所有请求共享套接字。
  • 连接池减少了请求延迟(如果HTTP / 2不可用)。
  • 透明GZIP缩小了下载大小。
  • 响应缓存完全避免网络重复请求。

当网络很麻烦时,OkHttp坚持不懈:它将从常见的连接问题中无声地恢复。如果您的服务有多个IP地址,如果第一次连接失败,OkHttp将尝试备用地址。这对于IPv4 + IPv6和冗余数据中心中托管的服务是必需的。OkHttp启动具有现代TLS功能(SNI,ALPN)的新连接,并在握手失败时回退到TLS 1.0。

使用OkHttp很简单。它的请求/响应API采用流畅的构建器和不变性设计。它支持同步阻塞调用和带回调的异步调用。

OkHttp支持Android 2.3及更高版本。对于Java,最低要求是1.7

引自官方网站:okhttp官网

二、简单使用:
1.导入jar包
 <dependency>
      <groupId>com.squareup.okhttp3</groupId>
      <artifactId>okhttp</artifactId>
      <version>3.11.0</version>
 </dependency>
2.使用步骤
  1. 创建okHttp单例

    采用枚举的方式创建线程安全的okHttpClient单例

/**
 * Description :
 * 获取okHttpClient单例
 * @author : Jeason
 * @date : Created in 2018/10/25 11:16
*/

public enum OkHttpClientObject {
    CLIENT;
    
    private OkHttpClient clientInstance;

    private Integer connectTimeout_time = 10;
    private Integer writeTimeout_time = 10;
    private Integer readTimeout_time = 30;

    OkHttpClientObject() {
        clientInstance = new OkHttpClient.Builder()
                .connectTimeout(connectTimeout_time, TimeUnit.SECONDS)
                .writeTimeout(writeTimeout_time, TimeUnit.SECONDS)
                .readTimeout(readTimeout_time, TimeUnit.SECONDS)
                .retryOnConnectionFailure(true)
                .build();
    }

    public OkHttpClient getClientInstance() {
        return clientInstance;
    }
}
  1. 获取okHttpClient实例
private final OkHttpClient client = (OkHttpClient) OkHttpClientObject.CLIENT.getClientInstance();
  1. 创建request请求
//创建请求
Request request = new Request.Builder()
        .header("User-Agent", "*****")
        .addHeader("Accept", "*****")
        .url(url)
    	.get()
        .build();
  1. 发起请求,分为同步和异步两种方式
//同步执行请求,将响应结果存放到response中
Call call = client.newCall(request);
Response response = call.execute();

//异步请求
Call call = client.newCall(request);
call.enqueue(new Callback() {
    @Override
    public void onFailure(Call call, IOException e) {
        System.out.println("请求失败");
    }

    @Override
    public void onResponse(Call call, Response response) throws IOException {
        System.out.println(response.body().string());
    }
});
demo代码:
public class OkHttpClientDemo {
    //json传输方式
    private final MediaType JSON = MediaType.parse("application/json; charset=utf-8");

    //获取okHttpClient对象
    private final OkHttpClient client = (OkHttpClient) OkHttpClientObject.CLIENT
            .getClientInstance();
   
   private String result;

    /**
     * get形式,同步执行
     */
    public String get(String url) throws IOException {
        //创建请求
        Request request = new Request.Builder()
                .header("User-Agent", "*****")
                .addHeader("Accept", "*****")
                .url(url)
                .build();
        //同步执行请求,将响应结果存放到response中
         Call call = client.newCall(request);
        Response response = call.execute();

        if (response.isSuccessful()) {
            //处理response的响应消息
            return response.body().string();
        } else {
            throw new IOException("Unexpected code " + response);
        }
    }

    /**
     * post形式
     */
     public String post(String url, String message) throws IOException {
        //请求体传输json格式的数据
        RequestBody requestBody = RequestBody.create(JSON, message);
        //创建请求
        Request request = new Request.Builder()
                .url(url)
                .header("User-Agent", "*****")
                .addHeader("Accept", "*****")
                .post(requestBody)
                .build();

        //同步请求

        Call call = client.newCall(request);
        Response response = call.execute();

        if (response.isSuccessful()) {
            return response.body().string();
        } else {
            throw new IOException("Unexpected code " + response);
        }
    }

    /**
     * 异步发起请求
     */
    public void pool(String url) {
        //创建请求
        Request request = new Request.Builder()
                .url(url)
                .build();

        //异步请求
        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                System.out.println("请求失败");
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                System.out.println(response.body().string());
            }
        });
    }

}
参考文章:
  1. https://square.github.io/okhttp/3.x/okhttp/
  2. https://juejin.im/entry/5728441d128fe1006058b6b9
  3. https://blog.youkuaiyun.com/ahjxly/article/details/76460315
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值