1.OkHttp源码解析

发布于 2022年 04月 12日 15:29

GitHub地址:github.com/square/okht…

square.github.io/okhttp/

同步请求:

OkHttpClient okHttpClient = new OkHttpClient.Builder().build();//1.创建OkHttp对象
Request request = new Request.Builder().url(url).build(); //2.创建Request对象
Response response = okHttpClient.newCall(request).execute(); //3.发送请求

调用okHttpClient的newCall(request)方法实际上是调用了RealCall的newRealCall()

@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.eventListener = client.eventListenerFactory().create(call);
  return call;
}

newRealCall方法直接返回一个RealCall对象

下面是RealCall的execute():

@Override 
public Response execute() throws IOException {
  synchronized (this) {
    if (executed) throw new IllegalStateException("Already Executed");
    executed = true;
  }
  captureCallStackTrace();
  eventListener.callStart(this);
  try {
    client.dispatcher().executed(this);
    Response result = getResponseWithInterceptorChain();
    if (result == null) throw new IOException("Canceled");
    return result;
  } catch (IOException e) {
    eventListener.callFailed(this, e);
    throw e;
  } finally {
    client.dispatcher().finished(this);
  }
}

异步请求:

OkHttpClient okHttpClient = new OkHttpClient();
Request request = new Request.Builder().url(url).build();
okHttpClient.newCall(request).enqueue(new Callback() {
    @Override
    public void onFailure(Call call, IOException e) {

    }
    @Override
    public void onResponse(Call call, Response response) throws IOException {
        Log.d("TAG", response.body().string());
    }
});


推荐文章