1.OkHttp源码解析

1.OkHttp源码解析

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());    }});


免责声明:本网信息来自于互联网,目的在于传递更多信息,并不代表本网赞同其观点。其原创性以及文中陈述文字和内容未经本站证实,对本文以及其中全部或者部分内容、文字的真实性、完整性、及时性本站不作任何保证或承诺,并请自行核实相关内容。本站不承担此类作品侵权行为的直接责任及连带责任。如若本网有任何内容侵犯您的权益,请及时联系我们,本站将会在24小时内处理完毕。
相关文章
返回顶部