OkHttp源碼分析(一)綜述

導(dǎo)圖

OkHttp源碼分析.png

簡介

OkHttp是Square公司開源的一款面向Java和Android平臺的HTTP客戶端,是目前最主流的網(wǎng)絡(luò)框架之一。在Android4.4中,HttpUrlConnection底層已經(jīng)默認使用okhttp實現(xiàn)。

特點

  • 支持HTTP2/SPDY黑科技
  • socket自動選擇最好路線,并支持自動重連
  • 擁有自動維護的socket連接池,減少握手次數(shù)
  • 擁有隊列線程池,輕松寫并發(fā)
  • 擁有Interceptors輕松處理請求與響應(yīng)(比如透明GZIP壓縮,LOGGING)
  • 基于Headers的緩存策略

基本用法

創(chuàng)建OkHttpClient對象

OkHttpClient為OkHttp初始的配置中心,通過它可以完成初始參數(shù)的配置,設(shè)置超時時間,添加自定義攔截器,初始化線程池,代理等工作

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;
  }

兩種創(chuàng)建方式

  • 默認創(chuàng)建。直接new OkHttpClient,將使用Okhttp的默認配置
  • 自定義創(chuàng)建。通過指定一個Builder

創(chuàng)建Request對象

Request用于描述一個HTTP請求,比如請求的方法是"GET"還是"POST",請求的URL,請求的header,請求的body,請求的緩存策略等

//創(chuàng)建一個Request
Request request = new Request.Builder()
        .url(url)
        .build();

創(chuàng)建Call對象

Call是一次HTTP請求的Task,它會執(zhí)行網(wǎng)絡(luò)請求以獲得響應(yīng)。OkHttp中的網(wǎng)絡(luò)請求執(zhí)行Call既可以同步進行,也可以異步進行。調(diào)用call.execute()將直接執(zhí)行網(wǎng)絡(luò)請求,阻塞直到獲得響應(yīng)。而調(diào)用call.enqueue()傳入回調(diào),則會將Call放入一個異步執(zhí)行隊列,由ExecutorService在后臺執(zhí)行。

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

執(zhí)行網(wǎng)絡(luò)請求并獲取響應(yīng)

同步請求

同步請求會對當(dāng)前線程產(chǎn)生阻塞,直到請求響應(yīng)返回

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

異步請求

異步請求將提交到線程池中執(zhí)行

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

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 關(guān)于okhttp是一款優(yōu)秀的網(wǎng)絡(luò)請求框架,關(guān)于它的源碼分析文章有很多,這里分享我在學(xué)習(xí)過程中讀到的感覺比較好的文章...
    蕉下孤客閱讀 3,737評論 2 38
  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 136,697評論 19 139
  • Android 自定義View的各種姿勢1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 179,351評論 25 708
  • 參考Android網(wǎng)絡(luò)請求心路歷程Android Http接地氣網(wǎng)絡(luò)請求(HttpURLConnection) 一...
    合肥黑閱讀 21,736評論 7 63
  • 昨天朋友說了個事,讓我挺感慨的。 她室友上午沒出門,下午出去發(fā)現(xiàn)放在樓下的自行車不見了,于是便報警了。 警察很快趕...
    云深不知處_Julie閱讀 831評論 1 1

友情鏈接更多精彩內(nèi)容