自助建网站软件平台,内容网站最新好用的cms,互联网推广模式,网站手机页面做多大https://square.github.io/okhttp/square.github.iosquare/okhttpgithub.com0 概述okhttp是一个现代的网络请求框架Http/2 支持 所有访问同一个主机的Request都共用一个socketconnection pool 连接池 减少请求延迟GZIP 压缩数据#xff0c;减少传输所用的带宽Response Cac…https://square.github.io/okhttp/square.github.iosquare/okhttpgithub.com0 概述okhttp是一个现代的网络请求框架Http/2 支持 所有访问同一个主机的Request都共用一个socketconnection pool 连接池 减少请求延迟GZIP 压缩数据减少传输所用的带宽Response Cache 避免重复性的Request1 使用GetOkHttpClient 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();}
}Postpublic static final MediaType JSON MediaType.get(application/json; charsetutf-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();}
}Asyncprivate 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 OkHttpClientdispatcherinterceptorsnetworkInterceptorsconnectionPoolproxynewCall()2.2 CallResponse execute()enqueue(Callback responseCallback)2.3 RequesturlmethodheadersbodytagcacheControl2.4 Responserequestprotocolcodemessageheadersbodyhandshake2.5 RealInterceptorChaininterceptorstransmitterindexrequestcallexchange2.6 InterceptorResponse intercept(Chain chain)2.7 CacheDiskLruCache cache;2.8 ConnectionRoute route();Socket socket();Handshake handshake();Protocol protocol();connectSocketsourcesinkconnectionPool3 架构中间层OKhttp 通过很多中间拦截器来对 Request Response 进行加工实现了数据的 流式链式处理生产者分发器调度器 通过不同状态的 任务队列 来调度任务readyCalls runningCalls消费者缓存拦截器类似责任链的效果链式处理链式返回