天天看點

簡單實用的OkHttp3入門精簡教程

<a href="http://blog.csdn.net/lfdfhl/article/details/51671038">自定義View系列教程00–推翻自己和過往,重學自定義View</a>

<a href="http://blog.csdn.net/lfdfhl/article/details/51324275">自定義View系列教程01–常用工具介紹</a>

<a href="http://blog.csdn.net/lfdfhl/article/details/51347818">自定義View系列教程02–onMeasure源碼詳盡分析</a>

<a href="http://blog.csdn.net/lfdfhl/article/details/51393131">自定義View系列教程03–onLayout源碼詳盡分析</a>

<a href="http://blog.csdn.net/lfdfhl/article/details/51435968">自定義View系列教程04–Draw源碼分析及其實踐</a>

<a href="http://blog.csdn.net/lfdfhl/article/details/51508727">自定義View系列教程05–示例分析</a>

<a href="http://blog.csdn.net/lfdfhl/article/details/51559847">自定義View系列教程06–詳解View的Touch事件處理</a>

<a href="http://blog.csdn.net/lfdfhl/article/details/51603088">自定義View系列教程07–詳解ViewGroup分發Touch事件</a>

<a href="http://blog.csdn.net/lfdfhl/article/details/51656492">自定義View系列教程08–滑動沖突的産生及其處理</a>

<a href="http://blog.csdn.net/lfdfhl/article/details/52415390">探索Android軟鍵盤的疑難雜症</a>

<a href="http://blog.csdn.net/lfdfhl/article/details/53332936">深入探讨Android異步精髓Handler</a>

<a href="http://blog.csdn.net/lfdfhl/article/details/52673536">詳解Android主流架構不可或缺的基石</a>

<a href="http://blog.csdn.net/lfdfhl/article/details/53143114">站在源碼的肩膀上全解Scroller工作機制</a>

<a href="http://blog.csdn.net/lfdfhl/article/details/52735103">Android多分辨率适配架構(1)— 核心基礎</a>

<a href="http://blog.csdn.net/lfdfhl/article/details/52877866">Android多分辨率适配架構(2)— 原理剖析</a>

<a href="http://blog.csdn.net/lfdfhl/article/details/53046113">Android多分辨率适配架構(3)— 使用指南</a>

本文将用最簡的代碼和語句介紹OkHttp3的常用基本操作。

導入OkHttp3

添權重限

請注意:假若你看到此處不明白為什麼需要做這些準備工作,那麼請點選浏覽器右上角的八叉 ( X )

請注意:測試時,請将url替換成您自己的可用位址

什麼是攔截器呢?

攔截器能對Call進行監測、改寫、重試連接配接;它能夠對請求和響應進行二次加工。通俗地說:攔截器是請求和回複之間的一道門——送出請求時資料需要從這道門出去;接收響應時資料需要從這道門進來。當然,當資料(不論進出)經過這道門時,該門可對資料進行某些操作。

OkHttp3常用的攔截器分為:

Application Interceptors 應用攔截器

Network Interceptors 網絡攔截器

這兩個攔截器有什麼差別呢?

Application interceptors 應用攔截器

Don’t need to worry about intermediate responses like redirects and retries.

不關心中間過程的響應,如重定向和重試

Are always invoked once, even if the HTTP response is served from the cache.

總是隻調用一次,即使HTTP響應是從緩存中擷取

Observe the application’s original intent. Unconcerned with OkHttp-injected headers like If-None-Match.

關注應用程式的初衷. 不關心OkHttp注入的頭資訊如: If-None-Match.

Permitted to short-circuit and not call Chain.proceed().

允許短路且不調用Chain.proceed()

Permitted to retry and make multiple calls to Chain.proceed().

允許重試,多次調用 Chain.proceed()

Able to operate on intermediate responses like redirects and retries.

能夠操作中間過程的響應,如重定向和重試.

Not invoked for cached responses that short-circuit the network.

當網絡短路傳回緩存響應時不被調用

Observe the data just as it will be transmitted over the network.

隻觀察在網絡上傳輸的資料.

Access to the Connection that carries the request.

攜帶請求通路連接配接

攔截器使用場景

為request統一添加header

檢查response判定使用者登入資訊是否失效,并用Dialog提示使用者登入

重寫響應頭和改變響應體。但不是很推薦這麼做,因為可能違反web伺服器的期望。

繼續閱讀