okhttp 连接池_okhttp 源码分析
生活随笔
收集整理的這篇文章主要介紹了
okhttp 连接池_okhttp 源码分析
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
https://square.github.io/okhttp/?square.github.iosquare/okhttp?github.com
0 概述
okhttp是一個現代的網絡請求框架
- Http/2 支持 所有訪問同一個主機的Request都共用一個socket
- connection pool 連接池 減少請求延遲
- GZIP 壓縮數據,減少傳輸所用的帶寬
- Response Cache 避免重復性的Request
1 使用
Get
OkHttpClient client = new OkHttpClient();String run(String url) throws IOException {Request request = new Request.Builder().url(url).build();try (Response response = client.newCall(request).execute()) {return response.body().string();} }Post
public static final MediaType JSON= MediaType.get("application/json; charset=utf-8");OkHttpClient client = new OkHttpClient();String post(String url, String json) throws IOException {RequestBody body = RequestBody.create(json, JSON);Request request = new Request.Builder().url(url).post(body).build();try (Response response = client.newCall(request).execute()) {return response.body().string();} }Async
private final OkHttpClient client = new OkHttpClient();public void run() throws Exception {Request request = new Request.Builder().url("http://publicobject.com/helloworld.txt").build();client.newCall(request).enqueue(new Callback() {@Override public void onFailure(Call call, IOException e) {e.printStackTrace();}@Override public void onResponse(Call call, Response response) throws IOException {try (ResponseBody responseBody = response.body()) {if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);Headers responseHeaders = response.headers();for (int i = 0, size = responseHeaders.size(); i < size; i++) {System.out.println(responseHeaders.name(i) + ": " + responseHeaders.value(i));}System.out.println(responseBody.string());}}});}2 源碼
2.0 請求過程
2.1 OkHttpClient
- dispatcher
- interceptors
- networkInterceptors
- connectionPool
- proxy
- newCall()
2.2 Call
- Response execute()
- enqueue(Callback responseCallback)
2.3 Request
- url
- method
- headers
- body
- tag
- cacheControl
2.4 Response
- request
- protocol
- code
- message
- headers
- body
- handshake
2.5 RealInterceptorChain
- interceptors
- transmitter
- index
- request
- call
- exchange
2.6 Interceptor
- Response intercept(Chain chain)
2.7 Cache
- DiskLruCache cache;
2.8 Connection
- Route route();
- Socket socket();
- Handshake handshake();
- Protocol protocol();
- connectSocket
- source
- sink
- connectionPool
3 架構
- 中間層
- OKhttp 通過很多中間攔截器來對 Request Response 進行加工
- 實現了數據的 流式鏈式處理
- 生產者
- 分發器
- 調度器 通過不同狀態的 任務隊列 來調度任務
- readyCalls runningCalls
- 消費者
- 緩存
- 攔截器
- 類似責任鏈的效果,鏈式處理,鏈式返回
總結
以上是生活随笔為你收集整理的okhttp 连接池_okhttp 源码分析的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 1997年nba选秀顺位名单(以数据重新
- 下一篇: 业精于勤的意思