1.okhttp的具体用法
首先需要在gradle文件中添加依赖,一个是OkHttp库,一个是Okio库,后者是前者通信的基础。首先我们先看一下OkHttp的具体用法.
1).get请求
OkHttpClient client =new OkHttpClient();
Request request =new Request.Builder()
.url("这里是请求的链接")
.build();
Response response =client.newCall(request).execute();
String responseData =response.body().string();
首先需要创建一个OkHttpClient 对象,如果需要发送http请求,还需要创建一个Request对象,在build()之前有很多连缀方法来丰富Request对象,在这里我们只用了url()传入了目标网络地址。然后使用OkHttpClient 的newCall()方法来创建一个Call对象,并且调用它的execute()方法来发送请求并且获取数据,Response对象就是服务器返回的数据。这里的execute()方法是同步请求方法,如果需要使用异步请求需要使用Call对象的enqueue()方法 ,并且配合Handler进行回调使用,实际中使用异步请求的情况也比较多。
2).post请求
ResponseBody responseBody =new FormBody.Builder()
.add("键","值")
.build();
Request request =new Request.Builder()
.url("这里是请求的链接")
.post(responseBody)
.build();
post请求稍微比get请求复杂一点,主要是要在ResponseBody 中添加需要传入的参数,其余的操作就和get请求一样了。
2.okhttp的请求过程
1.)从请求开始分析
当我们访问网络的是时候需要newOkHttpClient.newCall(request)的execute()或者enqueue()方法。当我们调用newCall(),实际上是返回的一个RealCall对象,实际上调用的enqueue()和execute()也是RealCall的方法。
@Override
public Call newCall(Request request){
return new RealCall(this, request);
}
void enqueue(Callback response Callback, boolean forWebSocket){
synchronized(this) {
if(executed) throw new IllegalStateException("Already Executed");
executed =true;
}
client.dispatcher().enqueue(new AsyncCall(responseCallback, forWebSocket));
}
可以看到最终的请求是dispatcher来完成的。这里面最重要的就是enqueue()方法。
2)Dispatcher调度器
Dispacther主要用于控制并发的请求,主要维护的变量如下
/** 最大并发请求数*/
private int maxRequests = 64;
/** 每个主机最大请求数*/
private int maxRequestsPerHost = 5;
/** 消费者线程池 */
private ExecutorService executorService;
/** 将要运行的异步请求队列 */
private final Deque<AsyncCall> readyAsyncCalls = new ArrayDeque<>();
/**正在运行的异步请求队列 */
private final Deque<AsyncCall> runningAsyncCalls = new ArrayDeque<>();
/** 正在运行的同步请求队列 */
private final Deque<RealCall> runningSyncCalls = new ArrayDeque<>();
public Dispatcher(ExecutorService executorService) {
this.executorService = executorService;
}
public Dispatcher() {
}
public synchronized ExecutorService executorService() {
if (executorService == null) {
executorService = new ThreadPoolExecutor(0, Integer.MAX_VALUE, 60, TimeUnit.SECONDS,
new SynchronousQueue<Runnable>(), Util.threadFactory("OkHttp Dispatcher", false));
}
return executorService;
}
Dispatcher有两个构造函数,可以使用自己设定的线程池,如果线程池为null的时候,在网络请求前会自己创建一个线程池,这个线程池适合处理耗时比较少的任务,因为任务处理速度大于任务提交速度可以避免新的线程的创建,以免内存被占满。
synchronized void enqueue(AsyncCall call) {
if (runningAsyncCalls.size() < maxRequests && runningCallsForHost(call) < maxRequestsPerHost) {
runningAsyncCalls.add(call);
executorService().execute(call);
} else {
readyAsyncCalls.add(call);
}
}
在调度器中,当异步请求队列中的数量小于最大请求数并且正运行的主机数小于5时,则把请求加入线程池中,并且执行,否则就只是加入线程池,进行等待。
AsyncCall
传入线程池的AsyncCall 对象时RealCall的内部类,他也实现了execute()方法。
@Override protected void execute() {
boolean signalledCallback = false;
try {
Response response = getResponseWithInterceptorChain();
if (retryAndFollowUpInterceptor.isCanceled()) {
signalledCallback = true;
responseCallback.onFailure(RealCall.this, new IOException("Canceled"));
} else {
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);
}
}
}
在第四行中运行了getResponseWithInterceptorChain()方法,他返回了一个Response类型的参数,即是在这里向服务器发起请求的,因为设计到拦截器,这里不做讨论。最终finally中代码最后始终会运行,finished()方法如下。
void finished(AsyncCall call) {
finished(runningAsyncCalls, call, true);
}
...
private <T> void finished(Deque<T> calls, T call, boolean promoteCalls) {
int runningCallsCount;
Runnable idleCallback;
synchronized (this) {
if (!calls.remove(call)) throw new AssertionError("Call wasn't in-flight!");
if (promoteCalls) promoteCalls();
runningCallsCount = runningCallsCount();
idleCallback = this.idleCallback;
}
if (runningCallsCount == 0 && idleCallback != null) {
idleCallback.run();
}
}
在第五行中,从队列中移除了Call实例,第六行中因为传入的参数promoteCalls为真,所以会执行 promoteCalls()方法
private void promoteCalls() {
if (runningAsyncCalls.size() >= maxRequests) return; // Already running max capacity.
if (readyAsyncCalls.isEmpty()) return; // No ready calls to promote.
for (Iterator<AsyncCall> i = readyAsyncCalls.iterator(); i.hasNext(); ) {
AsyncCall call = i.next();
if (runningCallsForHost(call) < maxRequestsPerHost) {
i.remove();
runningAsyncCalls.add(call);
executorService().execute(call);
}
if (runningAsyncCalls.size() >= maxRequests) return; // Reached max capacity.
}
}
promoteCalls主要作用就是从readyAsyncCalls线程池中获取下一个请求,并且放在了runningAsyncCalls线程池中,并且调用了execute()方法处理。
如何进行网络请求
上文说到AsyncCall对象的execute()中运行了getResponseWithInterceptorChain()方法,进行了网络请求。
Response getResponseWithInterceptorChain() throws IOException {
// Build a full stack of interceptors.
List<Interceptor> interceptors = new ArrayList<>(); //这是一个List,是有序的
interceptors.addAll(client.interceptors());//首先添加的是用户添加的全局拦截器
interceptors.add(retryAndFollowUpInterceptor); //错误、重定向拦截器
//桥接拦截器,桥接应用层与网络层,添加必要的头、
interceptors.add(new BridgeInterceptor(client.cookieJar()));
//缓存处理,Last-Modified、ETag、DiskLruCache等
interceptors.add(new CacheInterceptor(client.internalCache()));
//连接拦截器
interceptors.add(new ConnectInterceptor(client));
//从这就知道,通过okHttpClient.Builder#addNetworkInterceptor()传进来的拦截器只对非网页的请求生效
if (!forWebSocket) {
interceptors.addAll(client.networkInterceptors());
}
//真正访问服务器的拦截器
interceptors.add(new CallServerInterceptor(forWebSocket));
Interceptor.Chain chain = new RealInterceptorChain(
interceptors, null, null, null, 0, originalRequest);
return chain.proceed(originalRequest);
}
这里创建一个关于拦截器的集合,首先将前面的client.interceptors()全部加入其中,在还有创建 RealCall时的retryAndFollowUpInterceptor加入其中,接着还创建并添加了BridgeInterceptor、CacheInterceptor、ConnectInterceptor、CallServerInterceptor,通过求最后RealInterceptorChain的proceed(Request)来执行整个interceptor chain,可见把这个拦截器链搞清楚,整体流程也就明朗了。这里我们只看CallServerInterceptor拦截器的功能,因为它时主要向服务器发送请求的拦截器。
@Override public Response intercept(Chain chain) throws IOException {
HttpCodec httpCodec = ((RealInterceptorChain) chain).httpStream();
StreamAllocation streamAllocation = ((RealInterceptorChain) chain).streamAllocation();
Request request = chain.request();
long sentRequestMillis = System.currentTimeMillis();
httpCodec.writeRequestHeaders(request);
if (HttpMethod.permitsRequestBody(request.method()) && request.body() != null) {
Sink requestBodyOut = httpCodec.createRequestBody(request, request.body().contentLength());
BufferedSink bufferedRequestBody = Okio.buffer(requestBodyOut);
request.body().writeTo(bufferedRequestBody);
bufferedRequestBody.close();
}
httpCodec.finishRequest();
Response response = httpCodec.readResponseHeaders()
.request(request)
.handshake(streamAllocation.connection().handshake())
.sentRequestAtMillis(sentRequestMillis)
.receivedResponseAtMillis(System.currentTimeMillis())
.build();
int code = response.code();
if (forWebSocket && code == 101) {
// Connection is upgrading, but we need to ensure interceptors see a non-null response body.
response = response.newBuilder()
.body(Util.EMPTY_RESPONSE)
.build();
} else {
response = response.newBuilder()
.body(httpCodec.openResponseBody(response))
.build();
}
if ("close".equalsIgnoreCase(response.request().header("Connection"))
|| "close".equalsIgnoreCase(response.header("Connection"))) {
streamAllocation.noNewStreams();
}
if ((code == 204 || code == 205) && response.body().contentLength() > 0) {
throw new ProtocolException(
"HTTP " + code + " had non-zero Content-Length: " + response.body().contentLength());
}
return response;
}
这部分就是从服务器发起请求的源码,最终返回Response,然而这里只是介绍了okhttp的如何请求,其实拦截器链才是整个框架的精髓。
这里我们总结一下okhttp的请求过程:
newOkHttpClient.newCall(request).enqueue()方法
1.首先通过OkHttpClient创建一个Call对象,实际上是一个RealCall
2.然后调用enqueue()方法,最终是调用client.dispatcher().enqueue()方法,主要是实现对任务的调度
3.最终通过拦截器实现对网络的请求