美文网首页Android Network
OkHttp源码分析(一)综述

OkHttp源码分析(一)综述

作者: J__Beyond | 来源:发表于2017-05-06 17:56 被阅读60次

    导图

    OkHttp源码分析.png

    简介

    OkHttp是Square公司开源的一款面向Java和Android平台的HTTP客户端,是目前最主流的网络框架之一。在Android4.4中,HttpUrlConnection底层已经默认使用okhttp实现。

    特点

    • 支持HTTP2/SPDY黑科技
    • socket自动选择最好路线,并支持自动重连
    • 拥有自动维护的socket连接池,减少握手次数
    • 拥有队列线程池,轻松写并发
    • 拥有Interceptors轻松处理请求与响应(比如透明GZIP压缩,LOGGING)
    • 基于Headers的缓存策略

    基本用法

    创建OkHttpClient对象

    OkHttpClient为OkHttp初始的配置中心,通过它可以完成初始参数的配置,设置超时时间,添加自定义拦截器,初始化线程池,代理等工作

    public OkHttpClient() {
        this(new Builder());
      }
      OkHttpClient(Builder builder) {
        this.dispatcher = builder.dispatcher;
        this.proxy = builder.proxy;
        this.protocols = builder.protocols;
        this.connectionSpecs = builder.connectionSpecs;
        this.interceptors = Util.immutableList(builder.interceptors);
        this.networkInterceptors = Util.immutableList(builder.networkInterceptors);
        this.proxySelector = builder.proxySelector;
        this.cookieJar = builder.cookieJar;
        this.cache = builder.cache;
        this.internalCache = builder.internalCache;
        this.socketFactory = builder.socketFactory;
    
        boolean isTLS = false;
        for (ConnectionSpec spec : connectionSpecs) {
          isTLS = isTLS || spec.isTls();
        }
        if (builder.sslSocketFactory != null || !isTLS) {
          this.sslSocketFactory = builder.sslSocketFactory;
          this.certificateChainCleaner = builder.certificateChainCleaner;
        } else {
          X509TrustManager trustManager = systemDefaultTrustManager();
          this.sslSocketFactory = systemDefaultSslSocketFactory(trustManager);
          this.certificateChainCleaner = CertificateChainCleaner.get(trustManager);
        }
        this.hostnameVerifier = builder.hostnameVerifier;
        this.certificatePinner = builder.certificatePinner.withCertificateChainCleaner(
            certificateChainCleaner);
        this.proxyAuthenticator = builder.proxyAuthenticator;
        this.authenticator = builder.authenticator;
        this.connectionPool = builder.connectionPool;
        this.dns = builder.dns;
        this.followSslRedirects = builder.followSslRedirects;
        this.followRedirects = builder.followRedirects;
        this.retryOnConnectionFailure = builder.retryOnConnectionFailure;
        this.connectTimeout = builder.connectTimeout;
        this.readTimeout = builder.readTimeout;
        this.writeTimeout = builder.writeTimeout;
        this.pingInterval = builder.pingInterval;
      }
    

    两种创建方式

    • 默认创建。直接new OkHttpClient,将使用Okhttp的默认配置
    • 自定义创建。通过指定一个Builder

    创建Request对象

    Request用于描述一个HTTP请求,比如请求的方法是"GET"还是"POST",请求的URL,请求的header,请求的body,请求的缓存策略等

    //创建一个Request
    Request request = new Request.Builder()
            .url(url)
            .build();
    

    创建Call对象

    Call是一次HTTP请求的Task,它会执行网络请求以获得响应。OkHttp中的网络请求执行Call既可以同步进行,也可以异步进行。调用call.execute()将直接执行网络请求,阻塞直到获得响应。而调用call.enqueue()传入回调,则会将Call放入一个异步执行队列,由ExecutorService在后台执行。

    //new call
    Call call = mOkHttpClient.newCall(request); 
    

    执行网络请求并获取响应

    同步请求

    同步请求会对当前线程产生阻塞,直到请求响应返回

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

    异步请求

    异步请求将提交到线程池中执行

    call.enqueue(new Callback(){
        @Override
        public void onResponse(final Response response) throws IOException{
               //String htmlStr =  response.body().string();
        }
    
        @Override
        public void onFailure(Request request, IOException e) {
    
        }
    });
    

    更多用法请参考 http://www.cnblogs.com/ct2011/p/3997368.html

    相关文章

      网友评论

        本文标题:OkHttp源码分析(一)综述

        本文链接:https://www.haomeiwen.com/subject/qlfytxtx.html