综上
//创建了Github接口的代理类 GitHub github = retrofit.create(GitHub.class); //执行接口的方法,其实就是调用了代理类的方法,并最终返回了一个OKhttpCall对象 //而这个对象就是对Okhttp的封装 Call<List<Contributor>> call = github.contributors("square", "retrofit"); 0x02 执行结果上文中获取到OKhttpCall对象,它只是把接口请求过程进行了封装,并没有真正的获取到接口数据。要获取到接口数据还需要调用OkHttpCall.execute方法
List<Contributor> contributors = call.execute().body(); Call.execute 或 Call.enqueue这里的请求过程与前文中《源码分析OKHttp执行过程》介绍的是类似的。接一下
打开OkHttpCall.execute方法
@Override public Response<T> execute() throws IOException { okhttp3.Call call; synchronized (this) { if (executed) throw new IllegalStateException("Already executed."); executed = true; if (creationFailure != null) { if (creationFailure instanceof IOException) { throw (IOException) creationFailure; } else if (creationFailure instanceof RuntimeException) { throw (RuntimeException) creationFailure; } else { throw (Error) creationFailure; } } call = rawCall; if (call == null) { try { call = rawCall = createRawCall(); } catch (IOException | RuntimeException | Error e) { throwIfFatal(e); // Do not assign a fatal error to creationFailure. creationFailure = e; throw e; } } } if (canceled) { call.cancel(); } return parseResponse(call.execute()); }这里的执行逻辑也很简单
使用synchronized进行同步操作
进行异常处理
调用createRawCall 创建 okhttp3.Call 对象
执行 okhttp 的Call.execute方法,并解析response后返回请求结果
同样地,异步请求操作也是类似的
打开OkHttpCall.enqueue方法
@Override public void enqueue(final Callback<T> callback) { checkNotNull(callback, "callback == null"); okhttp3.Call call; Throwable failure; synchronized (this) { if (executed) throw new IllegalStateException("Already executed."); executed = true; call = rawCall; failure = creationFailure; if (call == null && failure == null) { try { //创建okhttp网络请求 call = rawCall = createRawCall(); } catch (Throwable t) { throwIfFatal(t); failure = creationFailure = t; } } } if (failure != null) { callback.onFailure(this, failure); return; } if (canceled) { call.cancel(); } //最终是执行了OkHttp中的call.enqueue方法 //并回调相应的接口 call.enqueue(new okhttp3.Callback() { @Override public void onResponse(okhttp3.Call call, okhttp3.Response rawResponse) { Response<T> response; try { response = parseResponse(rawResponse); } catch (Throwable e) { throwIfFatal(e); callFailure(e); return; } try { callback.onResponse(OkHttpCall.this, response); } catch (Throwable t) { t.printStackTrace(); } } @Override public void onFailure(okhttp3.Call call, IOException e) { callFailure(e); } private void callFailure(Throwable e) { try { callback.onFailure(OkHttpCall.this, e); } catch (Throwable t) { t.printStackTrace(); } } }); }这个方法其实最终都是执行了okhttp的相应方法。
0x03 总结Retrofit 其实一种更加高级的网络应用框架,通过代理模式简化了接口的定义,无需提供接口的具体实现就可以完成网络接口请求的执行。它的底层实际上是封装了 okhttp 的执行过程,也把对网络的操作进行了封装,而对于程序猿来说只需要关注业务逻辑,对网络请求的具体实现不必关心。