okhttp篇1: OkhttpClient

public class OkHttpExample {
    public void doSimpleRequest() {
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url("http://www.baidu.com")
                .build();
        // 同步请求一个Request    
        try(Response response = client.newCall(request).execute()) {
            System.out.println("reponse header:"+response.headers());
            System.out.println("reponse body:"+response.body().string());
            Thread.sleep(TimeUnit.MINUTES.toMillis(5));
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

这个例子的主要部分:

  1. 创建OkHttpClient。
  2. 调用client.newCall,返回RealCall。
  3. 调用RealCall.execute方法,返回Response。

接下来的Okhttp学习就围绕这3点慢慢讲了。

对于第一点OkhttpClient,先从OkHttpClient的属性开始。

final Dispatcher dispatcher;
final @Nullable Proxy proxy;
final List<Protocol> protocols;
final List<ConnectionSpec> connectionSpecs;
final List<Interceptor> interceptors;
final List<Interceptor> networkInterceptors;
final EventListener.Factory eventListenerFactory;
final ProxySelector proxySelector;
final CookieJar cookieJar;
final @Nullable Cache cache;
final @Nullable InternalCache internalCache;
final SocketFactory socketFactory;
final @Nullable SSLSocketFactory sslSocketFactory;
final @Nullable CertificateChainCleaner certificateChainCleaner;
final HostnameVerifier hostnameVerifier;
final CertificatePinner certificatePinner;
final Authenticator proxyAuthenticator;
final Authenticator authenticator;
final ConnectionPool connectionPool;
final Dns dns;
final boolean followSslRedirects;
final boolean followRedirects;
final boolean retryOnConnectionFailure;
final int connectTimeout;
final int readTimeout;
final int writeTimeout;
final int pingInterval;
  1. Dispatcher: 负责管理OkHttpClient所发起的请求调度,内部的具体实现是一个线程池。Dispatcher负责控制每一个host同时最多只能发起5个请求,同时最多只能发起64个请求(5,64是默认参数,可设置)。
  2. Proxy
  3. List<Protocol>: 支持的协议,默认为[http1.1,http2.0]。这里如果要自定义,则一定要包括http1.1。
  4. ConnectionSpec:用来指定Socket的配置,比如当url为https的时候,需要指定TLS的版本号和加密方式。
  5. interceptors: 位于okhttp自身拦截器之前。
  6. networkInterceptors:在正式发起网络请求的拦截器之前。
  7. Cache
  8. ConnectionPool: 连接池。
  9. retryOnConnectionFailure。
  10. connectTimeout,readTimeout,writeTimeout。

后面学习完之后,上面的选项会逐渐补充完整。

下一篇,先讲Dispatcher。

okhttp篇2:Dispatcher_yolan6824的博客-CSDN博客

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值