OkHttp
是Square开源框架之一,想必大家对它都很熟悉。它有同步及异步两种请求数据方式,具体使用如下。
public static void main(String... args) throws Exception {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(url)
.build();
//采用同步方式请求数据
Response response = client.newCall(request).execute();
//采用异步方式请求数据
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
}
@Override
public void onResponse(Call call, Response response) throws IOException {
}
});
}
1、Call的创建
在OkHttp
中,每一个请求对应着一个Call
,它是一个接口,具体实现在RealCall
中。我们通过client.newCall(request)
就可以创建一个RealCall
对象,同步及异步请求就是通过RealCall
的execute
及enqueue
这两个方法来实现的。
@Override public Call newCall(Request request) {
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 call = new RealCall(client, originalRequest, forWebSocket);
call.transmitter = new Transmitter(client, call);
return call;
}
2、同步请求
通过client.newCall(request).execute()
这样一句代码就可以从网络请求数据,是不是很简单,下面就来梳理它的实现。
@Override public Response execute() throws IOException {
//每个Call对应着一次请求,只能在同一Call对象内调用一次本方法
synchronized (this) {
if (executed) throw new IllegalStateException("Already Executed");
executed = true;
}
captureCallStackTrace();
//Okio读写数据超时监听,防止一直阻塞,由于设置的值为0,所以timeout会一直运行下去除非抛异常
timeout.enter();
transmitter.callStart();
try {
//添加到请求队列中
client.dispatcher().executed(this);
//进行数据请求并返回
Response result = getResponseWithInterceptorChain();
//如果Response为空则抛异常