介绍
OkHttp是Android中使用非常广泛的一个网络框架,如果使用HttpUrlConnection可能会有些繁杂,使用okhttp可以轻松解决网络链接问题。
基本用法
引入依赖
compile group: 'com.squareup.okhttp3', name: 'okhttp', version: '3.8.0'
compile group: 'com.squareup.okio', name: 'okio', version: '1.8.0'
异步Get请求
Request.Builder builder = new Request.Builder()
.url("http://www.baidu.com/");
builder.method("GET",null);
Request request = builder.build();
OkHttpClient client = new OkHttpClient();
Call mCall = client.newCall(request);
mCall.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Toast.makeText(MainActivity.this, "失败了", Toast.LENGTH_SHORT).show();
}
@Override
public void onResponse(Call call, Response response) throws IOException {
String body = response.body().string();
Toast.makeText(MainActivity.this, body, Toast.LENGTH_SHORT).show();
}
});
异步Post请求
RequestBody requestBody = new FormBody.Builder()
.add("param","abc")
.build();
Request postRequest = new Request.Builder()
.url("http://www.baidu.com")
.post(requestBody)
.build();
//其他的代码和get一样,不贴了
post请求的参数需要构建一个requestBody对象添加参数,其他的和get请求是一样的。
异步上传文件
//定义文件类型
public static final MediaType MEDIA_TYPE_PLAIN = MediaType.parse("text/plain;charset=utf-8");
//创建文件对象
File file = new File(Environment.getExternalStorageDirectory(),"test.txt");
//构造post方法中发送的文件对象
RequestBody fileBody = RequestBody.create(MEDIA_TYPE_PLAIN,file);
异步下载文件
@Override
public void onResponse(Call call, Response response) throws IOException {
InputStream is = response.body().byteStream();
FileOutputStream fos = null;
String filePath = "";
try{
if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
filePath = Environment.getExternalStorageDirectory().getAbsolutePath();
}else{
filePath = getFilesDir().getAbsolutePath();
}
File file = new File(filePath,"file.jpg");
if(null != file){
fos = new FileOutputStream(file);
byte[] buffer = new byte[1024];
int len = 0;
while((len = is.read(buffer)) != -1){
fos.write(buffer,0,len);
}
fos.flush();
}
}catch (Exception e){
e.printStackTrace();
}
}
在response对象中获取文件输出流,输出到文件就可以了。
设置超时时间
一般进行网络操作的时候在一定时间内没有返回就可以认为超时了,可以关闭连接节省资源,使用okhttp的Builder可以很方便的完成这些设置:
OkHttpClient.Builder builder = new OkHttpClient.Builder()
.connectTimeout(5L, TimeUnit.SECONDS)
.writeTimeout(5L,TimeUnit.SECONDS)
.readTimeout(10L,TimeUnit.SECONDS)
.cache(new Cache(new File("/path/aaa"),cacheSize));
取消请求
使用call.cancel()可以取消正在执行的call;Request.Builder中可以指定tag标签,之后可以使用OkHttpClient,cancel(tag),来取消所有带tag的call。
源码解析
异步请求过程
先来看一下异步请求过程的源码,入口为client.newCall()方法。
//call对象是调用newCall方法创建出来的,Call为一个接口,实际上返回的是一个RealCall对象
@Override
public Call newCall(Request request) {
return new RealCall(this, request, false /* for web socket */);
}
通过call对象调用enqueue()方法,开始网络请求的过程
...
//RealCall里的方法
@Override public void enqueue(Callback responseCallback) {
synchronized (this) {
if (executed) throw new IllegalStateException("Already Executed");
executed = true;
}
captureCallStackTrace();
//这里先看一下AsyncCall对象的结构
client.dispatcher().enqueue(new AsyncCall(responseCallback));
}
final class AsyncCall extends NamedRunnable {
//保存了回调函数对象
private final Callback responseCallback;
AsyncCall(Callback responseCallback) {
super("OkHttp %s", redactedUrl());
this.responseCallback = responseCallback;
}
String host() {
return originalRequest.url().host();
}
Request request() {
return originalRequest;
}
RealCall get() {
return RealCall.this;
}
@Override protected void execute() {
...
}
}
在分析enqueue()方法之前,我们先看一下child.dispatcher()方法干了些啥。
public Dispatcher dispatcher() {
return dispatcher;
}
final Dispatcher dispatcher;
//直接返回了一个Dispatcher对象,主要看下这个类里的参数和方法
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<>();
//请求流程中会直接调用到enqueue方法
synchronized void enqueue(AsyncCall call) {
//正在运行的请求小于最大并发请求
if (runningAsyncCalls.size() < maxRequests && runningCallsForHost(call) < maxRequestsPerHost) {
//直接请求
runningAsyncCalls.add(call);
executorService().execute(call);
} else {
//加入等待队列排队
readyAsyncCalls.add(call);
}
}
}
直接请求会调用executorService().execute(call),看下具体实现。
public synchronized ExecutorService executorService() {
if (executorService == null) {
//创建了一个线程池,类似CachedThreadPool
executorService = new ThreadPoolExecutor(0, Integer.MAX_VALUE, 60, TimeUnit.SECONDS,
new SynchronousQueue<Runnable>(), Util.threadFactory("OkHttp Dispatcher", false));
}
return executorService;
}
//执行过程是通过线程池调用的,执行时会继续调用到AsyncCall对象中的execute()方法
@Override protected void execute() {
boolean signalledCallback = false;
try {
//由于这个方法内部返回了Response对象,可以看出此方法内进行了实际请求网络的操作
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 getResponseWithInterceptorChain() throws IOException {
// Build a full stack of interceptors.
//添加拦截器
List<Interceptor> interceptors = new ArrayList<>();
interceptors.addAll(client.interceptors());
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));
//通过拦截器链式调用,最后得到Response对象
Interceptor.Chain chain = new RealInterceptorChain(
interceptors, null, null, null, 0, originalRequest);
return chain.proceed(originalRequest);
}
通过拦截器去调用网络请求,返回response对象,调用回调之后会执行到finish()方法:
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) {
//会在异步执行call队列中移除执行完的此call对象
if (!calls.remove(call)) throw new AssertionError("Call wasn't in-flight!");
//传进来的promoteCalls为true,还会执行promoteCalls()方法
if (promoteCalls) promoteCalls();
runningCallsCount = runningCallsCount();
idleCallback = this.idleCallback;
}
if (runningCallsCount == 0 && idleCallback != null) {
idleCallback.run();
}
}
看下promoteCalls()方法里的内容。
private void promoteCalls() {
//如果达到了最大线程池 跳出
if (runningAsyncCalls.size() >= maxRequests) return; // Already running max capacity.
if (readyAsyncCalls.isEmpty()) return; // No ready calls to promote.
//遍历异步call等待序列,取出每一个call
for (Iterator<AsyncCall> i = readyAsyncCalls.iterator(); i.hasNext(); ) {
AsyncCall call = i.next();
//检测当前Host的并发线程数量是否超过最大值
if (runningCallsForHost(call) < maxRequestsPerHost) {
i.remove();
//添加到异步执行线程并执行
runningAsyncCalls.add(call);
executorService().execute(call);
}
if (runningAsyncCalls.size() >= maxRequests) return; // Reached max capacity.
}
}
在这个方法里可以取出未执行的call进行异步执行。
接下来看一下Response对象返回的具体过程。
Response getResponseWithInterceptorChain() throws IOException {
// Build a full stack of interceptors.
//新建了一个拦截器集合
List<Interceptor> interceptors = new ArrayList<>();
interceptors.addAll(client.interceptors());
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);
return chain.proceed(originalRequest);
}
会继续调用chain.proceed()方法进行下一步调用,这个对象是RealInterceptorChain,看下实现的方法。
@Override public Response proceed(Request request) throws IOException {
return proceed(request, streamAllocation, httpCodec, connection);
}
public Response proceed(Request request, StreamAllocation streamAllocation, HttpCodec httpCodec,
RealConnection connection) throws IOException {
...
// Call the next interceptor in the chain.
// 通过拦截器链去获取response对象
// 实际获得Response对象的操作应该是在拦截器链的末尾的intercept中
RealInterceptorChain next = new RealInterceptorChain(
interceptors, streamAllocation, httpCodec, connection, index + 1, request);
Interceptor interceptor = interceptors.get(index);
Response response = interceptor.intercept(next);
// Confirm that the next interceptor made its required call to chain.proceed().
if (httpCodec != null && index + 1 < interceptors.size() && next.calls != 1) {
throw new IllegalStateException("network interceptor " + interceptor
+ " must call proceed() exactly once");
}
// Confirm that the intercepted response isn't null.
if (response == null) {
throw new NullPointerException("interceptor " + interceptor + " returned null");
}
return response;
}
由上边的代码可以看到拦截器链的末尾是一个CallServerInterceptor拦截器,能力有限,里面具体的内容不分析了 可以看下这篇博客做下参考。
Okhttp之CallServerInterceptor简单分析