1、OkHttp3的基本使用
//1.1 GET请求
public void get() {
//1、构建request
Request request = new Request.Builder()
.url("https://blog.csdn.net/baidu_31093133")
.get()
.build();
//2、构建OkHttpClient
OkHttpClient okHttpClient = new OkHttpClient();
//3、构建Call
Call call = okHttpClient.newCall(request);
//4、发送异步请求
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
}
@Override
public void onResponse(Call call, Response response) throws IOException {
String str = response.body().toString();//注意toString方法只能调用一次
Log.i("LHD", "异步GET = " + str);
}
});
//5、同步请求使用call.execute();
}
//1.2 POST请求
public void post() {
//步骤同GET请求,只是多了一个构建请求体的步骤
//OKHTTP3可以使用FormBody非常方便的构建请求体
RequestBody requestBody = new FormBody.Builder()
.add("key1", "value2")//添加请求体1
.add("key2", "value2")//添加请求体2
.build();
Request request = new Request.Builder().url("url").post(requestBody).build();
OkHttpClient okHttpClient = new OkHttpClient();
Call call = okHttpClient.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
}
@Override
public void onResponse(Call call, Response response) throws IOException {
}
});
}
//1.3 上传文件
public void upload() {
//上传本身就是一个post操作,只是上传文件的时候我们需要指定一个MediaType
//MediaType的取值可参考http://www.iana.org/assignments/media-types/media-types.xhtml
File file = new File("filePath");
MediaType mediaType = MediaType.parse("image/png");
Request request = new Request.Builder().url("url").post(RequestBody.create(mediaType, file)).build();
OkHttpClient okHttpClient = new OkHttpClient();
okHttpClient.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
}
@Override
public void onResponse(Call call, Response response) throws IOException {
}
});
}
//1.4 上传多种类型文件
public void uploadMulti() {
File file = new File("filePath");
MediaType mediaType = MediaType.parse("image/png");
RequestBody requestBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
//String name, String value
.addFormDataPart("key1", "value1")
//String name, @Nullable String filename, RequestBody body
.addFormDataPart("image1", "value2", RequestBody.create(mediaType, file))
.build();
Request request = new Request.Builder()
.header("head1", "value")
.url("url").post(requestBody).build();
OkHttpClient okHttpClient = new OkHttpClient();
okHttpClient.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
}
@Override
public void onResponse(Call call, Response response) throws IOException {
}
});
}
//1.5 下载
public void downLoad() {
Request request = new Request.Builder().url("url").build();
OkHttpClient okHttpClient = new OkHttpClient();
okHttpClient.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
}
@Override
public void onResponse(Call call, Response response) throws IOException {
//得到response后将流写入到我们的文件中
InputStream inputStream = response.body().byteStream();
//...写入流的操作
}
});
}
//1.6 取消请求
public void cancel() {
//使用call的cancel方法即可
}
相信上面的用法大家都非常清楚,接下来我们对OkHttp3的源码进行解析。
2、OkHttp3的源码分析之请求流程
我们可以看到不管是post还是get,最终都是要调用call的enqueue方法(异步)或者execute方法来发起请求,所以我们从构建Call对象的okHttpClient.newCall(request)方法开始分析。
2.1 RealCall
Call call = okHttpClient.newCall(request);
点进去看一看,发现实际上返回的是一个RealCall对象
@Override public Call newCall(Request request) {
return RealCall.newRealCall(this, request, false /* for web socket */);
}
而我们的enqueue方法和execute就是这个RealCall对象的两个方法
final class RealCall implements Call {
@Override public Response execute() throws IOException{...}
@Override public void enqueue(Callback responseCallback){...}
}
我们先看enqueue方法
原来是调用了Dispatcher对象的的enqueue方法,接下来我们分析Dispatcher对象
2.2 Dispatcher
2.2.1 内部变量
public final class Dispatcher {
private int maxRequests = 64;
private int maxRequestsPerHost = 5;
private @Nullable Runnable idleCallback;
/** Executes calls. Created lazily. */
private @Nullable ExecutorService executorService;
/** Ready async calls in the order they'll be run. */
private final Deque<AsyncCall> readyAsyncCalls = new ArrayDeque<>();
/** Running asynchronous calls. Includes canceled calls that haven't finished yet. */
private final Deque<AsyncCall> runningAsyncCalls = new ArrayDeque<>();
/** Running synchronous calls. Includes canceled calls that haven't finished yet. */
private final Deque<RealCall> runningSyncCalls = new ArrayDeque<>();
}
Dispatcher对象内部维护了几个重要的网络请求参数
变量名 | 含义 |
---|---|
maxRequests | 最大并发请求数64 |
maxRequestsPerHost | 每个主机的最大请求数5 |
executorService | 线程池 |
readyAsyncCalls | 已经准备好将要运行的异步请求队列 |
runningAsyncCalls | 正在运行的异步请求队列 |
runningSyncCalls | 正在运行的同步请求队列 |
2.2.2 构造方法
可以看到Dispatcher有两个构造方法,一个无参构造函数一个传入了ExecutorService对象的构造函数。
我们可以通过Dispatcher(ExecutorService executorService)构造函数来传入自己设定的线程池,如果没有自己设定,OkHttp3会在发起请求前创建默认线程池。这个线程池比较适合执行大量的耗时比较少的任务。
enqueue 方法,注意这个方法每个版本是不一样的
void enqueue(AsyncCall call) {
synchronized (this) {
readyAsyncCalls.add(call);
// Mutate the AsyncCall so that it shares the AtomicInteger of an existing running call to
// the same host.
if (!call.get().forWebSocket) {
AsyncCall existingCall = findExistingCallWithHost(call.host());
if (existingCall != null) call.reuseCallsPerHostFrom(existingCall);
}
}
promoteAndExecute();
}
首先这是一个同步代码块,当前的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();
if (runningAsyncCalls.size() >= maxRequests) break; // Max capacity.
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;
}
if (runningAsyncCalls.size() >= maxRequests) break; // Max capacity.
我们看到有一个foreach循环,这个循环会把已经准备好执行的请求拿出来,最多只拿maxRequests个,然后加入到runningAsyncCalls这个表示正在执行的请求队列中,如果达到了最大请求个数maxRequests(64)个就直接break。
if (asyncCall.callsPerHost().get() >= maxRequestsPerHost) continue; // Host max capacity.
如果当前正在执行的异步请求的队列中对相同主机的请求数大于等于maxRequestsPerHost(5)个,则不会把这个请求加入到当前主机中去,而是进行下一次循环。
经过上面两个判断以后,把剩下的符合条件的请求从readyAsyncCalls这个准备好请求的队列中拿出来,放入到正在请求的队列runningAsyncCalls中和executableCalls队列中。
然后遍历executableCalls队列获取AsyncCall 对象,并调用AsyncCall 对象的executeOn方法。executeOn的参数是executorService()方法。
public synchronized ExecutorService executorService() {
if (executorService == null) {
executorService = new ThreadPoolExecutor(0, Integer.MAX_VALUE, 60, TimeUnit.SECONDS,
new SynchronousQueue<>(), Util.threadFactory("OkHttp Dispatcher", false));
}
return executorService;
}
这也是一个同步方法,返回一个线程池对象,这个线程池的最大容纳数量是最大值Integer.MAX_VALUE,但实际上不会达到这个值,因为已经在promoteAndExecute方法中做了判断
我们继续看asyncCall.executeOn(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);
transmitter.noMoreExchanges(ioException);
responseCallback.onFailure(RealCall.this, ioException);
} finally {
if (!success) {
client.dispatcher().finished(this); // This call is no longer running!
}
}
}
原来调用了executorService返回的线程池的execute方法。execute方法传入了this,也就是AsyncCall对象本身。
我们看一下AsyncCall对象,它是RealCall的内部类,它也实现了execute方法,所以真正执行的就是这个execute方法!
final class AsyncCall extends NamedRunnable {
@Override protected void execute() {
boolean signalledCallback = false;
transmitter.timeoutEnter();
try {
Response response = getResponseWithInterceptorChain();
signalledCallback = true;
responseCallback.onResponse(RealCall.this, response);
} catch (IOException e) {
if (signalledCallback) {
// Do not signal the callback twice!
Platform.get().log(INFO, "Callback failure for " + toLoggableString(), e);
} else {
responseCallback.onFailure(RealCall.this, e);
}
} finally {
client.dispatcher().finished(this);
}
}
}
}
可以看到无论AsyncCall 对象的execute方法执行结果是什么都会调用Dispatcher对象的finished方法,并且AsyncCall 类继承了NamedRunnable 类,而NamedRunnable 类实现了Runnable接口
我们再来看Dispatcher对象的finished方法
void finished(AsyncCall call) {
call.callsPerHost().decrementAndGet();
finished(runningAsyncCalls, call);
}
private <T> void finished(Deque<T> calls, T call) {
Runnable idleCallback;
synchronized (this) {
if (!calls.remove(call)) throw new AssertionError("Call wasn't in-flight!");
idleCallback = this.idleCallback;
}
boolean isRunning = promoteAndExecute();
if (!isRunning && idleCallback != null) {
idleCallback.run();
}
}
finished方法首先将此次请求从runningAsyncCalls队列中移除,然后执行promoteAndExecute方法,我们上面已经提到过,这个promoteAndExecute是为了从runningAsyncCalls队列中拿出符合要求的请求并放入到executableCalls和runningAsyncCalls队列中,交给线程池处理。
我们继续看AsyncCall 的execute方法:Response response = getResponseWithInterceptorChain();
很明显这一句代码就是在请求网络。并且从函数名字可以看出,这个getResponseWithInterceptorChain();方法必然也处理了拦截器。
我们做一个小总结:
1、Okhttp3发起异步网络请求的时候会调用dispatcher的enqueue方法,并且给这个方法传入了一个AsyncCall对象。
2、执行dispatcher的enqueue方法的时候会从readyAsyncCalls队列中拿出请求放到runningAsyncCalls队列中并生成一个线程池传给AsyncCall对象。
3、接着执行AsyncCall对象的executeOn方法,在这个方法里会调用线程池执行execute方法,并且把当前AsyncCall传给了线程池,由于AsyncCall类继承了NamedRunnable类并实现了Runnable接口,所以最终会调用AsyncCall的execute方法并发起真正的请求。
4、不管这个方法执行的结果如何都会调用dispatcher的finished方法,将已经执行的请求从runningAsyncCalls队列中移除,并继续从readyAsyncCalls队列中获取请求添加给runningAsyncCalls队列。
getResponseWithInterceptorChain 方法,Interceptor拦截器
Response getResponseWithInterceptorChain() throws IOException {
// Build a full stack of interceptors.
List<Interceptor> interceptors = new ArrayList<>();
interceptors.addAll(client.interceptors());
interceptors.add(new RetryAndFollowUpInterceptor(client));
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, transmitter, null, 0,
originalRequest, this, client.connectTimeoutMillis(),
client.readTimeoutMillis(), client.writeTimeoutMillis());
boolean calledNoMoreExchanges = false;
try {
Response response = chain.proceed(originalRequest);
...
return response;
} catch (IOException e) {
...
} finally {
...
}
}
}
首先我们看到OkHttp3首先添加了我们自己定义的所有拦截器interceptors.addAll(client.interceptors());接着根据我们提供给OkHttpClient.Builder的参数默认给我们添加了一些基础的拦截器,然后创建了RealInterceptorChain对象,并且设置了连接超时时间,读超时和写超时时间等参数后生成了一个Interceptor.Chain对象。
然后调用chain对象的proceed方法发起请求。
我们继续看proceed方法,并追踪到实现proceed方法的地方
public Response proceed(Request request, Transmitter transmitter, @Nullable Exchange exchange)
throws IOException {
...
// Call the next interceptor in the chain.
RealInterceptorChain next = new RealInterceptorChain(interceptors, transmitter, exchange,
index + 1, request, call, connectTimeout, readTimeout, writeTimeout);
Interceptor interceptor = interceptors.get(index);
Response response = interceptor.intercept(next);
...
return response;
}
这里是一段非常精彩的代码!
我们把大体框架先缕一缕
1、首先可以看到构建了一个RealInterceptorChain对象,并传递给Interceptor 的intercept方法,接着我们去看这个intercept方法的实现
2、
有好多个实现,我们发现这些就是刚才默认给我添加的那些基础拦截器!
我们点进第一个拦截器BridgeInterceptor去看
public final class BridgeInterceptor implements Interceptor {
private final CookieJar cookieJar;
public BridgeInterceptor(CookieJar cookieJar) {
this.cookieJar = cookieJar;
}
@Override public Response intercept(Chain chain) throws IOException {
Request userRequest = chain.request();
Request.Builder requestBuilder = userRequest.newBuilder();
RequestBody body = userRequest.body();
...
Response networkResponse = chain.proceed(requestBuilder.build());
...
return responseBuilder.build();
}
}
大家可以看到,这个拦截器的intercept方法使用传进来的chain对象,最后居然又调用了RealInterceptorChain对象的proceed方法!
3、RealInterceptorChain对象实现了Interceptor.Chain接口
public final class RealInterceptorChain implements Interceptor.Chain
总结、
1、首先构建了一个RealInterceptorChain对象
2、调用RealInterceptorChain的proceed方法来发起请求
3、在proceed中又生成了一个新的RealInterceptorChain对象并传递给第一个拦截器的intercept方法
4、第一个拦截器执行intercept方法的过程中再次调用了传进来的RealInterceptorChain对象的proceed方法
5、然后再次生成一个新的RealInterceptorChain对象并传递给第二个拦截器
6、再次执行第二个拦截器的intercept方法然后再次调用RealInterceptorChain对象的proceed方法
大家发现了吗?每次都会生成一个新的RealInterceptorChain对象,并且调用下一个拦截器,这样就会进行递归调用,直到调用完所有的拦截器!
那么这些拦截器的intercept方法到底干了些什么呢?这些拦截器到底起到了什么作用呢?这个RealInterceptorChain对象又到底是什么呢?
今天太晚了2019.3.18 1:27 ,请看下篇哦O(∩_∩)O~~