版本号:3.13.1
一.基本使用
//1.创建OkHttpClient对象val okHttpClient = OkHttpClient.Builder().readTimeout(5,TimeUnit.SECONDS).build()//2.创建Request对象val request = Request.Builder().url("www.baidu.com").build()//3.通过OkHttpClient将Request封装成Call对象val call = okHttpClient.newCall(request)//通过Call执行请求//同步请求val response = call.execute() Log.d("okhttp",response.body().toString())//异步请求call.enqueue(object :Callback{ override fun onFailure(call: Call, e: IOException) { } override fun onResponse(call: Call, response: Response) { Log.d("okhttp",response.body().toString()) } })
Call可以理解为Request和Response之间的桥梁,Http请求过程中可能有重定向和重试等操作,你的一个简单请求可能会产生多个请求和响应。OkHttp使用Call这一概念对此来建模:不论为了满足你的请求任务,中间做了多少次请求和响应,都算作一个Call。
二.源码分析
1.创建对象源码分析
不管是同步请求还是异步请求,都必须先创建OkHttpClient和Request对象,上面使用Build模式创建的,下面分别看一下各自的源码:
OkHttpClient.Builder().
public Builder() { //任务分发器 dispatcher = new Dispatcher(); protocols = DEFAULT_PROTOCOLS; connectionSpecs = DEFAULT_CONNECTION_SPECS; eventListenerFactory = EventListener.factory(EventListener.NONE); proxySelector = ProxySelector.getDefault(); if (proxySelector == null) { proxySelector = new NullProxySelector(); } cookieJar = CookieJar.NO_COOKIES; socketFactory = SocketFactory.getDefault(); hostnameVerifier = OkHostnameVerifier.INSTANCE; certificatePinner = CertificatePinner.DEFAULT; proxyAuthenticator = Authenticator.NONE; authenticator = Authenticator.NONE; //连接池 connectionPool = new ConnectionPool(); dns = Dns.SYSTEM; followSslRedirects = true; followRedirects = true; retryOnConnectionFailure = true; callTimeout = 0; //java7以后在数字中可以使用下划线,只是增加阅读性,没其他作用 connectTimeout = 10_000; readTimeout = 10_000; writeTimeout = 10_000; pingInterval = 0; }
Request.Builder()
public Builder() { this.method = "GET"; this.headers = new Headers.Builder(); }
build()方法,都是在该方法中创建各自的对象,在构造方法中将当前的build对象传入,然后把对应的属性值赋。下面以Request为例:
public Request build() { if (url == null) throw new IllegalStateException("url == null"); return new Request(this); }//Builder模式Request(Builder builder) {this.url = builder.url;this.method = builder.method;this.headers = builder.headers.build();this.body = builder.body;this.tags = Util.immutableMap(builder.tags); }
不管同步请求还是异步请求,都是调用Call的方法执行的,下面看一下Call对象的创建okHttpClient.newCall(request)
:
@Override public Call newCall(Request request) { //Call是一个接口,RealCall是它的实现类 return RealCall.newRealCall(this, request, false /* for web socket */); }static RealCall newRealCall(OkHttpClient client, Request originalRequest, boolean forWebSocket) { // Safely publish the Call instance to the EventListener. //创建RealCall对象,将client和request传入 RealCall call = new RealCall(client, originalRequest, forWebSocket); //设置监听器 call.eventListener = client.eventListenerFactory().create(call); return call; }private RealCall(OkHttpClient client, Request originalRequest, boolean forWebSocket) { this.client = client; this.originalRequest = originalRequest; this.forWebSocket = forWebSocket; //重定向拦截器 this.retryAndFollowUpInterceptor = new RetryAndFollowUpInterceptor(client); this.timeout = new AsyncTimeout() { @Override protected void timedOut() { cancel(); } }; this.timeout.timeout(client.callTimeoutMillis(), MILLISECONDS); }
从上面代码中可以看到Call的实现类为RealCall,它持有client和request。
上面创建对象的源码已经分析完了,下面就看一下具体请求的方法。
2.同步请求:call.execute()
@Override public Response execute() throws IOException { synchronized (this) { //同一个请求执行执行一遍,否则跑出异常 if (executed) throw new IllegalStateException("Already Executed"); executed = true; } ...... //当执行的请求开始的时候,回调监听中的方法 eventListener.callStart(this); try { //真正的请求是dispatcher.executed client.dispatcher().executed(this); Response result = getResponseWithInterceptorChain(); if (result == null) throw new IOException("Canceled"); return result; }...... finally { //执行完成以后从对列中移除请求 client.dispatcher().finished(this); } }public Dispatcher dispatcher() { return dispatcher; }//dispatcher.executedsynchronized void executed(RealCall call) { //将call加入到同步请求对列中 runningSyncCalls.add(call); }public final class Dispatcher { ...... //异步就绪对列 private final Deque<AsyncCall> readyAsyncCalls = new ArrayDeque<>(); //异步执行对列 private final Deque<AsyncCall> runningAsyncCalls = new ArrayDeque<>(); //同步执行对列 private final Deque<RealCall> runningSyncCalls = new ArrayDeque<>(); ...... }
同步请求调用
realCall.executed
方法,在该方法中调用dispatcher.executed
将realCall添加到同步运行对列中runningSyncCalls
然后调用getResponseWithInterceptorChain
获取响应报文。
3.异步请求: call.enqueue
@Override public void enqueue(Callback responseCallback) { synchronized (this) { //当前的call(创建的call)只能执行一次 if (executed) throw new IllegalStateException("Already Executed"); executed = true; } captureCallStackTrace(); eventListener.callStart(this); //封装成了AsyncCall,它就是一个Runable client.dispatcher().enqueue(new AsyncCall(responseCallback)); }
void enqueue(AsyncCall call) { synchronized (this) { //添加到就绪对列 readyAsyncCalls.add(call); ...... } } promoteAndExecute(); }private boolean promoteAndExecute() { assert (!Thread.holdsLock(this)); List<AsyncCall> executableCalls = new ArrayList<>(); boolean isRunning; synchronized (this) { //遍历就绪对列执行任务 for (Iterator<AsyncCall> i = readyAsyncCalls.iterator(); i.hasNext(); ) { AsyncCall asyncCall = i.next(); //如果请求大于最大的请求数 maxRequests = 64,不执行 if (runningAsyncCalls.size() >= maxRequests) break; // Max capacity. //请求的host不能大于maxRequestsPerHost = 5 if (asyncCall.callsPerHost().get() >= maxRequestsPerHost) continue; // Host max capacity. i.remove(); asyncCall.callsPerHost().incrementAndGet(); //没有大于最大请求数,添加到执行对列中 executableCalls.add(asyncCall); runningAsyncCalls.add(asyncCall); } isRunning = runningCallsCount() > 0; } //循环执行对列,执行具体的请求 for (int i = 0, size = executableCalls.size(); i < size; i++) { AsyncCall asyncCall = executableCalls.get(i); //执行任务,传入线程池 asyncCall.executeOn(executorService()); } return isRunning; }
异步请求的时候,通过
dispatcher.enqueue
方法将call(封装成了Runable(AsyncCall,它是RealCall的的内部类))添加到就绪对列中,然后循环就绪对列,如果现在执行的任务数没有超过最大的请求数(64)就添加到执行对列中,然后执行asyncCall.executeOn(executorService());
。
public synchronized ExecutorService executorService() { if (executorService == null) { //最大的线程数为 Integer.MAX_VALUE,上面已经限制最大的请求数为64所以这里的数量不会超过64 executorService = new ThreadPoolExecutor(0, Integer.MAX_VALUE, 60, TimeUnit.SECONDS, new SynchronousQueue<>(), Util.threadFactory("OkHttp Dispatcher", false)); } return executorService; }void executeOn(ExecutorService executorService) { assert (!Thread.holdsLock(client.dispatcher())); boolean success = false; try { //执行任务 executorService.execute(this); success = true; } catch (RejectedExecutionException e) { InterruptedIOException ioException = new InterruptedIOException("executor rejected"); ioException.initCause(e); eventListener.callFailed(RealCall.this, ioException); responseCallback.onFailure(RealCall.this, ioException); } finally { if (!success) { client.dispatcher().finished(this); // This call is no longer running! } } }
executorService.execute(this);
就是执行AsyncCall中的run()
方法
AsyncCall继承NamedRunnable,没有重写run()
方法,直接调用父类的,在父类的run()
方法中调用了一个execute();
方法,该方法是一个抽象方法,需要子类实现,所以实际执行的是AsyncCall.execute()
public abstract class NamedRunnable implements Runnable { ...... @Override public final void run() { String oldName = Thread.currentThread().getName(); Thread.currentThread().setName(name); try { execute(); } finally { Thread.currentThread().setName(oldName); } } protected abstract void execute(); }
下面就看一个AsyncCall.execute(),真正执行任务的方法:
//该方法在子线程中执行@Override protected void execute() { boolean signalledCallback = false; timeout.enter(); try { //获取响应报文 Response response = getResponseWithInterceptorChain(); if (retryAndFollowUpInterceptor.isCanceled()) { signalledCallback = true; responseCallback.onFailure(RealCall.this, new IOException("Canceled")); } else { signalledCallback = true; responseCallback.onResponse(RealCall.this, response); } }...... finally { //调用finished方法,将该请求从请求对列中移除 client.dispatcher().finished(this); } } }
从上面的代码分析我们可以得出:异步请求流程:
call.enqueue
->realCall.enqueue
->dispatcher.enqueue(AsyncCall call)
(AsyncCall本质就是一个Runable)在dispatcher.enqueue
方法中将call添加到就绪对列中,然后外遍历就绪对列,如果现在运行的任务没有超过最大请求数(64)就会把它加入到运行对列中runningAsyncCalls,然后调用asyncCall.executeOn(executorService())
(executorService()方法就是创建一个线程池),在executeOn
方法中会执行asyncCall,就是调用它的execute
方法。在该方法中真正的去执行任务,该方法是在子线程中执行的。
通过上面的分析我们可以得出大致的请求流程图如下:
请求流程图
不管是同步请求还是异步请求,都调用了dispatcher对应的方法,它里面维护了三个任务对列和一个线程池(用来执行异步请求),dispatcher维护着请求任务的添加和移除。
三.Okhttp中的拦截器
拦截器是Okhttp提供的一种强大的机制,它可以实现网络监听、请求以及响应重写、请求失败重试等功能。
Okhttp的拦截器分为两种:一种是应用拦截器(就是我们自定义的拦截器),另一种就是网络拦截器(是Okhttp内部提供给我们的拦截器,真正的网络请求就是通过这些网络拦截器来实现的)。
从上面的代码分析得出:不管是同步请求还是异步请求,最终都是通过getResponseWithInterceptorChain()
方法来获取Response的,该方法就是构建一个拦截器链。下面看一下该方法的代码:
//RealCall中的方法Response getResponseWithInterceptorChain() throws IOException { List<Interceptor> interceptors = new ArrayList<>(); //添加自定义的拦截器 interceptors.addAll(client.interceptors()); //添加okhttp提供给我们的网络拦截器 interceptors.add(retryAndFollowUpInterceptor); interceptors.add(new BridgeInterceptor(client.cookieJar())); interceptors.add(new CacheInterceptor(client.internalCache())); interceptors.add(new ConnectInterceptor(client)); if (!forWebSocket) { interceptors.addAll(client.networkInterceptors()); } interceptors.add(new CallServerInterceptor(forWebSocket)); //创建一个拦截器链对象,然后将拦截器集合传入 Interceptor.Chain chain = new RealInterceptorChain(interceptors, null, null, null, 0, originalRequest, this, eventListener, client.connectTimeoutMillis(), client.readTimeoutMillis(), client.writeTimeoutMillis()); return chain.proceed(originalRequest); }
创建好拦截器链以后调用了该对象的chain.proceed(originalRequest)
方法。该方法源码如下:
public Response proceed(Request request, StreamAllocation streamAllocation, HttpCodec httpCodec, RealConnection connection) throws IOException { ...... //又创建了一个拦截器链对象,注意此时传入的index = index + 1 RealInterceptorChain next = new RealInterceptorChain(interceptors, streamAllocation, httpCodec, connection, index + 1, request, call, eventListener, connectTimeout, readTimeout, writeTimeout); //顺序获取拦截器,然后调用拦截器的intercept方法 Interceptor interceptor = interceptors.get(index); Response response = interceptor.intercept(next); ...... return response; }
在
chain.proceed
方法中调用了interceptor.intercept(next);
方法,并将新创建的拦截器链对象传入,此时index为index + 1,这样就构成了依次调用拦截器集合的所用拦截器的intercept
方法。在该方法中完成对应的功能以后,调用下一个拦截器的intercept
方法,并将处理后的Response返回给上一个拦截器。
拦截器处理流程图
1.RetryAndFollowUpInterceptor(重定向拦截器)
该拦截器的主要作用就是:负责请求的重定向操作以及请求失败后的重试机制。
@Override public Response intercept(Chain chain) throws IOException { Request request = chain.request(); RealInterceptorChain realChain = (RealInterceptorChain) chain; Call call = realChain.call(); EventListener eventListener = realChain.eventListener(); //1.创建StreamAllocation 对象,该对象用于分配请求过程中的流 StreamAllocation streamAllocation = new StreamAllocation(client.connectionPool(), createAddress(request.url()), call, eventListener, callStackTrace); this.streamAllocation = streamAllocation; //重连次数 int followUpCount = 0; Response priorResponse = null; while (true) { ...... Response response; boolean releaseConnection = true; try { //2.调用RealInterceptorChain的proceed方法进行网络请求 response = realChain.proceed(request, streamAllocation, null, null); releaseConnection = false; }...... // 叠加先前的响应 if (priorResponse != null) { response = response.newBuilder() .priorResponse(priorResponse.newBuilder() .body(null) .build()) .build(); } Request followUp; try { //根据响应判断是否需要重新请求 followUp = followUpRequest(response, streamAllocation.route()); }...... if (followUp == null) { //不需要重新请求,直接返回response,结束while循环 streamAllocation.release(true); return response; } ...... //需要重新请求,先判断重新请求的次数是否超过设置的最大值,MAX_FOLLOW_UPS = 20 if (++followUpCount > MAX_FOLLOW_UPS) { //超过最大的重新请求次数,抛出异常 streamAllocation.release(true); throw new ProtocolException("Too many follow-up requests: " + followUpCount); } ...... //重新请求 if (!sameConnection(response, followUp.url())) { streamAllocation.release(false); streamAllocation = new StreamAllocation(client.connectionPool(), createAddress(followUp.url()), call, eventListener, callStackTrace); this.streamAllocation = streamAllocation; }...... request = followUp; priorResponse = response; } }
从RetryAndFollowUpInterceptor.intercept
方法得出主要做了以下几件事:
1.创建StreamAllocation对象。
2.调用RealInterceptorChain的
proceed
方法进行网络请求,该方法就会调用下一个拦截器的intercept
方法,依次调用,获取对应的Response。
intercept
方法有些类似递归调用,这里是不同拦截器对象的intercept
方法,这样就从上到下形成了一个链。
3.根据异常结果或者响应结果判断是否要进行重新请求。
2.BridgeInterceptor(桥接拦截器)
该拦截器的作用主要就是处理请求和响应
在RetryAndFollowUpInterceptor拦截器中创建StreamAllocation对象以后,就会调用chain.proceed
方法进行网络请求,其实就是调用下一个拦截器的intercept
方法,RetryAndFollowUpInterceptor的下一个拦截就是BridgeInterceptor,下面看一下它的intercept
代码:
@Override public Response intercept(Chain chain) throws IOException { Request userRequest = chain.request(); Request.Builder requestBuilder = userRequest.newBuilder(); RequestBody body = userRequest.body(); //1.为请求添加一些头信息 if (body != null) { MediaType contentType = body.contentType(); if (contentType != null) { requestBuilder.header("Content-Type", contentType.toString()); } long contentLength = body.contentLength(); if (contentLength != -1) { requestBuilder.header("Content-Length", Long.toString(contentLength)); requestBuilder.removeHeader("Transfer-Encoding"); } else { requestBuilder.header("Transfer-Encoding", "chunked"); requestBuilder.removeHeader("Content-Length"); } } if (userRequest.header("Host") == null) { requestBuilder.header("Host", hostHeader(userRequest.url(), false)); } if (userRequest.header("Connection") == null) { requestBuilder.header("Connection", "Keep-Alive"); } // If we add an "Accept-Encoding: gzip" header field we're responsible for also decompressing // the transfer stream. boolean transparentGzip = false; if (userRequest.header("Accept-Encoding") == null && userRequest.header("Range") == null) { transparentGzip = true; requestBuilder.header("Accept-Encoding", "gzip"); } List<Cookie> cookies = cookieJar.loadForRequest(userRequest.url()); if (!cookies.isEmpty()) { requestBuilder.header("Cookie", cookieHeader(cookies)); } if (userRequest.header("User-Agent") == null) { requestBuilder.header("User-Agent", Version.userAgent()); } //2.发送网络请求 Response networkResponse = chain.proceed(requestBuilder.build()); //3.解压响应数据,支持`gzip`,所以需要解压 HttpHeaders.receiveHeaders(cookieJar, userRequest.url(), networkResponse.headers()); Response.Builder responseBuilder = networkResponse.newBuilder() .request(userRequest); if (transparentGzip && "gzip".equalsIgnoreCase(networkResponse.header("Content-Encoding")) && HttpHeaders.hasBody(networkResponse)) { GzipSource responseBody = new GzipSource(networkResponse.body().source()); Headers strippedHeaders = networkResponse.headers().newBuilder() .removeAll("Content-Encoding") .removeAll("Content-Length") .build(); responseBuilder.headers(strippedHeaders); String contentType = networkResponse.header("Content-Type"); responseBuilder.body(new RealResponseBody(contentType, -1L, Okio.buffer(responseBody))); } return responseBuilder.build(); }
从BridgeInterceptor.intercept
方法得出主要做了以下几件事:
1.将用户构建的Request转化为能够进行网络访问的请求(添加一些头信息,如:
Connection
、Accept-Encoding
、Host
等)。2.将设置好的Request发送网络请求(调用
chan.proceed
)。3.将请求返回的Response转化为用户可用的Response(可能使用gzip压缩,需要解压)。
3.CacheInterceptor(缓存拦截器)
该拦截器的作用主要就是处理数据的缓存
在BridgeInterceptor.intercept
方法中构建好Request后就发送请求,就会调用CacheInterceptor.intercept
方法,该方法的代码为:
@Override public Response intercept(Chain chain) throws IOException { //如果设置了缓存就获取缓存 Response cacheCandidate = cache != null ? cache.get(chain.request()) : null; long now = System.currentTimeMillis(); //获取缓存策略,里面维护着一个networkRequest和cacheResponse CacheStrategy strategy = new CacheStrategy.Factory(now, chain.request(), cacheCandidate).get(); Request networkRequest = strategy.networkRequest; Response cacheResponse = strategy.cacheResponse; if (cache != null) { //如果有缓存,跟新一下缓存的各项指标,主要是缓存命中率 cache.trackResponse(strategy); } if (cacheCandidate != null && cacheResponse == null) { //有缓存,但是对应的Response 为null即缓存不符合要求,关闭该缓存 closeQuietly(cacheCandidate.body()); // The cache candidate wasn't applicable. Close it. } // 如果此时网络不可用,同时网络不可用,抛出一个504的错误 if (networkRequest == null && cacheResponse == null) { return new Response.Builder() .request(chain.request()) .protocol(Protocol.HTTP_1_1) .code(504) .message("Unsatisfiable Request (only-if-cached)") .body(Util.EMPTY_RESPONSE) .sentRequestAtMillis(-1L) .receivedResponseAtMillis(System.currentTimeMillis()) .build(); } //网络不可用,但是有缓存,直接返回缓存。 if (networkRequest == null) { return cacheResponse.newBuilder() .cacheResponse(stripBody(cacheResponse)) .build(); } //没有缓存,但是网路可用,发起网络请求 Response networkResponse = null; try { networkResponse = chain.proceed(networkRequest); } finally { // If we're crashing on I/O or otherwise, don't leak the cache body. if (networkResponse == null && cacheCandidate != null) { closeQuietly(cacheCandidate.body()); } } if (cacheResponse != null) { //如果网络请求返回的状态码为 HTTP_NOT_MODIFIED = 304,从缓存中获取数据 if (networkResponse.code() == HTTP_NOT_MODIFIED) { Response response = cacheResponse.newBuilder() .headers(combine(cacheResponse.headers(), networkResponse.headers())) .sentRequestAtMillis(networkResponse.sentRequestAtMillis()) .receivedResponseAtMillis(networkResponse.receivedResponseAtMillis()) .cacheResponse(stripBody(cacheResponse)) .networkResponse(stripBody(networkResponse)) .build(); networkResponse.body().close(); ...... } Response response = networkResponse.newBuilder() .cacheResponse(stripBody(cacheResponse)) .networkResponse(stripBody(networkResponse)) .build(); if (cache != null) { //如果请求可以缓存,就将网络请求后的数据添加到缓存 if (HttpHeaders.hasBody(response) && CacheStrategy.isCacheable(response, networkRequest)) { // Offer this request to the cache. CacheRequest cacheRequest = cache.put(response); return cacheWritingResponse(cacheRequest, response); } //如果请求方法缓存无效,从缓存中删除 if (HttpMethod.invalidatesCache(networkRequest.method())) { try { cache.remove(networkRequest); } catch (IOException ignored) { // The cache cannot be written. } } } return response; }@Override public Response intercept(Chain chain) throws IOException { //如果设置了缓存就获取缓存 Response cacheCandidate = cache != null ? cache.get(chain.request()) : null; long now = System.currentTimeMillis(); //获取缓存策略,里面维护着一个networkRequest和cacheResponse CacheStrategy strategy = new CacheStrategy.Factory(now, chain.request(), cacheCandidate).get(); Request networkRequest = strategy.networkRequest; Response cacheResponse = strategy.cacheResponse; if (cache != null) { //如果有缓存,跟新一下缓存的各项指标,主要是缓存命中率 cache.trackResponse(strategy); } if (cacheCandidate != null && cacheResponse == null) { //有缓存,但是对应的Response 为null即缓存不符合要求,关闭该缓存 closeQuietly(cacheCandidate.body()); // The cache candidate wasn't applicable. Close it. } // 如果此时网络不可用,同时缓存不可用,抛出一个504的错误 if (networkRequest == null && cacheResponse == null) { return new Response.Builder() .request(chain.request()) .protocol(Protocol.HTTP_1_1) .code(504) .message("Unsatisfiable Request (only-if-cached)") .body(Util.EMPTY_RESPONSE) .sentRequestAtMillis(-1L) .receivedResponseAtMillis(System.currentTimeMillis()) .build(); } //网络不可用,但是有缓存,直接返回缓存。 if (networkRequest == null) { return cacheResponse.newBuilder() .cacheResponse(stripBody(cacheResponse)) .build(); } //没有缓存,但是网路可用,发起网络请求 Response networkResponse = null; try { networkResponse = chain.proceed(networkRequest); } finally { // If we're crashing on I/O or otherwise, don't leak the cache body. if (networkResponse == null && cacheCandidate != null) { closeQuietly(cacheCandidate.body()); } } if (cacheResponse != null) { //如果网络请求返回的状态码为 HTTP_NOT_MODIFIED = 304,从缓存中获取数据 if (networkResponse.code() == HTTP_NOT_MODIFIED) { Response response = cacheResponse.newBuilder() .headers(combine(cacheResponse.headers(), networkResponse.headers())) .sentRequestAtMillis(networkResponse.sentRequestAtMillis()) .receivedResponseAtMillis(networkResponse.receivedResponseAtMillis()) .cacheResponse(stripBody(cacheResponse)) .networkResponse(stripBody(networkResponse)) .build(); networkResponse.body().close(); ...... } Response response = networkResponse.newBuilder() .cacheResponse(stripBody(cacheResponse)) .networkResponse(stripBody(networkResponse)) .build(); if (cache != null) { //如果请求可以缓存,就将网络请求后的数据添加到缓存 if (HttpHeaders.hasBody(response) && CacheStrategy.isCacheable(response, networkRequest)) { // Offer this request to the cache. CacheRequest cacheRequest = cache.put(response); return cacheWritingResponse(cacheRequest, response); } //如果请求方法缓存无效,从缓存中删除 if (HttpMethod.invalidatesCache(networkRequest.method())) { try { cache.remove(networkRequest); } catch (IOException ignored) { // The cache cannot be written. } } } return response; }
作者:慕涵盛华
链接:https://www.jianshu.com/p/073893ac22bd