okhttp 连接池_okhttp 源码分析
生活随笔
收集整理的這篇文章主要介紹了
okhttp 连接池_okhttp 源码分析
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
https://square.github.io/okhttp/?square.github.iosquare/okhttp?github.com
0 概述
okhttp是一個(gè)現(xiàn)代的網(wǎng)絡(luò)請(qǐng)求框架
- Http/2 支持 所有訪問(wèn)同一個(gè)主機(jī)的Request都共用一個(gè)socket
- connection pool 連接池 減少請(qǐng)求延遲
- GZIP 壓縮數(shù)據(jù),減少傳輸所用的帶寬
- Response Cache 避免重復(fù)性的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 請(qǐng)求過(guò)程
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 架構(gòu)
- 中間層
- OKhttp 通過(guò)很多中間攔截器來(lái)對(duì) Request Response 進(jìn)行加工
- 實(shí)現(xiàn)了數(shù)據(jù)的 流式鏈?zhǔn)教幚?/li>
- 生產(chǎn)者
- 分發(fā)器
- 調(diào)度器 通過(guò)不同狀態(tài)的 任務(wù)隊(duì)列 來(lái)調(diào)度任務(wù)
- readyCalls runningCalls
- 消費(fèi)者
- 緩存
- 攔截器
- 類(lèi)似責(zé)任鏈的效果,鏈?zhǔn)教幚?#xff0c;鏈?zhǔn)椒祷?/li>
總結(jié)
以上是生活随笔為你收集整理的okhttp 连接池_okhttp 源码分析的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 1997年nba选秀顺位名单(以数据重新
- 下一篇: rust废铁最快_Rust初体验,它确实