新聞中心
簡介

創(chuàng)新互聯(lián)公司是專業(yè)的柳河網(wǎng)站建設(shè)公司,柳河接單;提供做網(wǎng)站、成都做網(wǎng)站,網(wǎng)頁設(shè)計,網(wǎng)站設(shè)計,建網(wǎng)站,PHP網(wǎng)站建設(shè)等專業(yè)做網(wǎng)站服務(wù);采用PHP框架,可快速的進行柳河網(wǎng)站開發(fā)網(wǎng)頁制作和功能擴展;專業(yè)做搜索引擎喜愛的網(wǎng)站,專業(yè)的做網(wǎng)站團隊,希望更多企業(yè)前來合作!
Retrofit 是 Square 推出的 HTTP 框架,主要用于 Android 和 Java。Retrofit 將網(wǎng)絡(luò)請求變成方法的調(diào)用,使用起來非常簡潔方便。本文先簡要介紹一下 Retrofit 的用法,然后具體分析其源碼執(zhí)行的流程。
基本用法
Retrofit 把HTTP API 變成 Java 的接口。下面是 Retrofit 官網(wǎng)的一個例子:
- public interface GitHubService {
- @GET("users/{user}/repos")
- Call
> listRepos(@Path("user") String user);
- }
在 GithubService 接口中有一個方法 listRepos,這個方法用了 @GET 的方式注解,這表明這是一個 GET 請求。在后面的括號中的users/{user}/repos 是請求的路徑,其中的 {user} 表示的是這一部分是動態(tài)變化的,它的值由方法的參數(shù)傳遞過來,而這個方法的參數(shù)@Path("user") String user 即是用于替換 {user} 。另外注意這個方法的返回值是 Call>??梢钥闯?Retrofit 用注解的方式來描述一個網(wǎng)絡(luò)請求相關(guān)的參數(shù)。
上面才是開始,下面要發(fā)出這個網(wǎng)絡(luò)請求:
- Retrofit retrofit = new Retrofit.Builder()
- .baseUrl("https://api.github.com/")
- .addConverterFactory(GsonConverterFactory.create())
- .build();
- GitHubService service = retrofit.create(GitHubService.class);
- Call
> repos = service.listRepos("octocat");
- repos.enqueue(new Callback
>() {
- @Override
- public void onResponse(Call
> call, Response
> response) {
- }
- @Override
- public void onFailure(Call
> call, Throwable t) {
- }
- });
可以看出,先是構(gòu)建了一個 Retrofit 對象,其中傳入了 baseUrl 參數(shù),baseUrl 和上面的 GET 方法后面的路徑組合起來才是一個完整的 url。除了 baseUrl,還有一個 converterFactory,它是用于把返回的 http response 轉(zhuǎn)換成 Java 對象,對應(yīng)方法的返回值Call> 中的 List
Retrofit 的基本用法就是這樣,其它還有一些細節(jié)可以查看官網(wǎng)。
源碼分析
我***次接觸 Retrofit 的時候覺得這個東西挺神奇的,用法跟一般的網(wǎng)絡(luò)請求不一樣。下面就來看看 Retrofit 的源碼是怎么實現(xiàn)的。
Retrofit 的創(chuàng)建
從 Retrofit 的創(chuàng)建方法可以看出,使用的是 Builder 模式。Retrofit 中有如下的幾個關(guān)鍵變量:
- //用于緩存解析出來的方法
- private final Map
serviceMethodCache = new LinkedHashMap<>(); - //請求網(wǎng)絡(luò)的OKHttp的工廠,默認(rèn)是 OkHttpClient
- private final okhttp3.Call.Factory callFactory;
- //baseurl
- private final HttpUrl baseUrl;
- //請求網(wǎng)絡(luò)得到的response的轉(zhuǎn)換器的集合 默認(rèn)會加入 BuiltInConverters
- private final List
converterFactories; - //把Call對象轉(zhuǎn)換成其它類型
- private final List
adapterFactories; - //用于執(zhí)行回調(diào) Android中默認(rèn)是 MainThreadExecutor
- private final Executor callbackExecutor;
- //是否需要立即解析接口中的方法
- private final boolean validateEagerly;
再看一下Retrofit 中的內(nèi)部類 Builder 的 builder 方法:
- public Retrofit build() {
- if (baseUrl == null) {
- throw new IllegalStateException("Base URL required.");
- }
- okhttp3.Call.Factory callFactory = this.callFactory;
- if (callFactory == null) {
- //默認(rèn)創(chuàng)建一個 OkHttpClient
- callFactory = new OkHttpClient();
- }
- Executor callbackExecutor = this.callbackExecutor;
- if (callbackExecutor == null) {
- //Android 中返回的是 MainThreadExecutor
- callbackExecutor = platform.defaultCallbackExecutor();
- }
- // Make a defensive copy of the adapters and add the default Call adapter.
- List
adapterFactories = new ArrayList<>(this.adapterFactories); - adapterFactories.add(platform.defaultCallAdapterFactory(callbackExecutor));
- // Make a defensive copy of the converters.
- List
converterFactories = new ArrayList<>(this.converterFactories); - return new Retrofit(callFactory, baseUrl, converterFactories, adapterFactories,
- callbackExecutor, validateEagerly);
- }
在創(chuàng)建 Retrofit 的時候,如果沒有指定 OkHttpClient,會創(chuàng)建一個默認(rèn)的。如果沒有指定 callbackExecutor,會返回平臺默認(rèn)的,在 Android 中是 MainThreadExecutor,并利用這個構(gòu)建一個 CallAdapter加入 adapterFactories。
create 方法
有了 Retrofit 對象后,便可以通過 create 方法創(chuàng)建網(wǎng)絡(luò)請求接口類的實例,代碼如下:
- public
T create(final Class service) { - Utils.validateServiceInterface(service);
- if (validateEagerly) {
- //提前解析方法
- eagerlyValidateMethods(service);
- }
- return (T) Proxy.newProxyInstance(service.getClassLoader(), new Class>[] { service },
- new InvocationHandler() {
- private final Platform platform = Platform.get();
- @Override public Object invoke(Object proxy, Method method, Object... args)
- throws Throwable {
- // If the method is a method from Object then defer to normal invocation.如果是Object中的方法,直接調(diào)用
- if (method.getDeclaringClass() == Object.class) {
- return method.invoke(this, args);
- }
- //為了兼容 Java8 平臺,Android 中不會執(zhí)行
- if (platform.isDefaultMethod(method)) {
- return platform.invokeDefaultMethod(method, service, proxy, args);
- }
- //下面是重點,解析方法
- ServiceMethod serviceMethod = loadServiceMethod(method);
- OkHttpCall okHttpCall = new OkHttpCall<>(serviceMethod, args);
- return serviceMethod.callAdapter.adapt(okHttpCall);
- }
- });
create 方法接受一個 Class 對象,也就是我們編寫的接口,里面含有通過注解標(biāo)識的請求網(wǎng)絡(luò)的方法。注意 return 語句部分,這里調(diào)用了 Proxy.newProxyInstance 方法,這個很重要,因為用了動態(tài)代理模式。關(guān)于動態(tài)代理模式,可以參考這篇文章:http://www.codekk.com/blogs/d...。簡單的描述就是,Proxy.newProxyInstance 根據(jù)傳進來的 Class 對象生成了一個實例 A,也就是代理類。每當(dāng)這個代理類 A 執(zhí)行某個方法時,總是會調(diào)用 InvocationHandler(Proxy.newProxyInstance 中的第三個參數(shù)) 的invoke 方法,在這個方法中可以執(zhí)行一些操作(這里是解析方法的注解參數(shù)等),通過這個方法真正的執(zhí)行我們編寫的接口中的網(wǎng)絡(luò)請求。
方法解析和類型轉(zhuǎn)換
下面具體看一下在 invoke 中解析網(wǎng)絡(luò)請求方法的幾行。首先是 ServiceMethod serviceMethod = loadServiceMethod(method);,其中 loadServiceMethod 代碼如下:
- ServiceMethod loadServiceMethod(Method method) {
- ServiceMethod result;
- synchronized (serviceMethodCache) {
- result = serviceMethodCache.get(method);
- if (result == null) {
- result = new ServiceMethod.Builder(this, method).build();
- serviceMethodCache.put(method, result);
- }
- }
- return result;
- }
可以看出,這里是先到緩存中找,緩存中沒有再去創(chuàng)建。這里創(chuàng)建了 ServiceMethod 對象。ServiceMethod 用于把接口方法的調(diào)用轉(zhuǎn)換成一個 HTTP 請求。其實,在 ServiceMethod 中,會解析接口中方法的注解、參數(shù)等,它還有個 toRequest 方法,用于生成一個 Request 對象。這個 Request 對象就是 OkHttp 中的 Request,代表了一條網(wǎng)絡(luò)請求(Retrofit 實際上把真正請求網(wǎng)絡(luò)的操作交給了 OkHttp 執(zhí)行)。下面是創(chuàng)建 ServiceMethod 的部分代碼:
- public ServiceMethod build() {
- //獲取 callAdapter
- callAdapter = createCallAdapter();
- responseType = callAdapter.responseType();
- if (responseType == Response.class || responseType == okhttp3.Response.class) {
- throw methodError("'"
- + Utils.getRawType(responseType).getName()
- + "' is not a valid response body type. Did you mean ResponseBody?");
- }
- //獲取 responseConverter
- responseConverter = createResponseConverter();
- for (Annotation annotation : methodAnnotations) {
- //解析注解
- parseMethodAnnotation(annotation);
- //省略了一些代碼
- ...
- }
- }
在得到 ServiceMethod 對象后,把它連同方法調(diào)用的相關(guān)參數(shù)傳給了 OkHttpCall 對象,也就是這行代碼: OkHttpCall okHttpCall = new OkHttpCall<>(serviceMethod, args);。 下面介紹 OkHttpCall,OkHttpCall繼承于 Call 接口。Call 是Retrofit 的基礎(chǔ)接口,代表發(fā)送網(wǎng)絡(luò)請求與響應(yīng)調(diào)用,它包含下面幾個接口方法:
- Response
execute() throws IOException; //同步執(zhí)行請求 - void enqueue(Callback
callback); //異步執(zhí)行請求,callback 用于回調(diào) - boolean isExecuted(); //是否執(zhí)行過
- void cancel(); //取消請求
- boolean isCanceled(); //是否取消了
- Call
clone(); //克隆一條請求 - Request request(); //獲取原始的request
OkHttpCall 是 Call 的一個實現(xiàn)類,它里面封裝了 OkHttp 中的原生 Call,在這個類里面實現(xiàn)了 execute 以及 enqueue 等方法,其實是調(diào)用了 OkHttp 中原生 Call 的對應(yīng)方法。
接下來把 OkHttpCall 傳給 serviceMethod.callAdapter 對象,這里的callAdapter又是什么?在上面創(chuàng)建 ServiceMethod 的代碼中有一行代碼: callAdapter = createCallAdapter(),這里創(chuàng)建了 calladapter,在這個代碼內(nèi)部是根據(jù)方法的返回類型以及注解去尋找對應(yīng)的 CallAdapter,去哪里尋找?去 Retrofit 對象的 adapterFactories 集合中找。當(dāng)我們創(chuàng)建 Retrofit 的時候,可以調(diào)用 addCallAdapter 向 adapterFactories 中添加 CallAdapter。在前面的基本用法里面,我們并沒有添加任何 CallAdapter,但adapterFactories 中默認(rèn)會添加一個 ExecutorCallAdapterFactory,調(diào)用其 get 方法便可獲得 CallAdapter 對象。
那么 CallAdapter 是干嘛的呢?上面調(diào)用了adapt 方法,它是為了把一個 Call 轉(zhuǎn)換成另一種類型,比如當(dāng) Retrofit 和 RxJava 結(jié)合使用的時候,接口中方法可以返回 Observable
- public CallAdapter
> get(Type returnType, Annotation[] annotations, Retrofit retrofit) { - if (getRawType(returnType) != Call.class) {
- return null;
- }
- final Type responseType = Utils.getCallResponseType(returnType);
- return new CallAdapter
>() { - @Override public Type responseType() {
- return responseType;
- }
- @Override public
Call adapt(Call call) { - return new ExecutorCallbackCall<>(callbackExecutor, call);
- }
- };
- }
這個 ExecutorCallbackCall 接受一個 callbackExecutor(Android 中默認(rèn)為 MainThreadExecutor,把返回的數(shù)據(jù)傳回主線程) 和一個 call,也就是 OkhttpCall??聪?ExecutorCallbackCall 部分代碼:
- static final class ExecutorCallbackCall
implements Call { - final Executor callbackExecutor;
- final Call
delegate; - ExecutorCallbackCall(Executor callbackExecutor, Call
delegate) { - this.callbackExecutor = callbackExecutor;
- this.delegate = delegate;
- }
- @Override public void enqueue(final Callback
callback) { - if (callback == null) throw new NullPointerException("callback == null");
- delegate.enqueue(new Callback
() { - @Override public void onResponse(Call
call, final Response response) { - callbackExecutor.execute(new Runnable() {
- @Override public void run() {
- if (delegate.isCanceled()) {
- // Emulate OkHttp's behavior of throwing/delivering an IOException on cancellation.
- callback.onFailure(ExecutorCallbackCall.this, new IOException("Canceled"));
- } else {
- callback.onResponse(ExecutorCallbackCall.this, response);
- }
- }
- });
- }
- @Override public void onFailure(Call
call, final Throwable t) { - callbackExecutor.execute(new Runnable() {
- @Override public void run() {
- callback.onFailure(ExecutorCallbackCall.this, t);
- }
- });
- }
- });
- }
在 enqueue 方法中,調(diào)用了 OkHttpCall 的 enqueue,所以這里相當(dāng)于靜態(tài)的代理模式。OkHttpCall 中的 enqueue 其實又調(diào)用了原生的 OkHttp 中的 enqueue,這里才真正發(fā)出了網(wǎng)絡(luò)請求,部分代碼如下:
- @Override public void enqueue(final Callback
callback) { - if (callback == null) throw new NullPointerException("callback == null");
- //真正請求網(wǎng)絡(luò)的 call
- okhttp3.Call call;
- Throwable failure;
- synchronized (this) {
- if (executed) throw new IllegalStateException("Already executed.");
- executed = true;
- //省略了部分發(fā)代碼
- ...
- call = rawCall;
- //enqueue 異步執(zhí)行
- call.enqueue(new okhttp3.Callback() {
- @Override public void onResponse(okhttp3.Call call, okhttp3.Response rawResponse)
- throws IOException {
- Response
response; - try {
- //解析數(shù)據(jù) 會用到 conveterFactory,把 response 轉(zhuǎn)換為對應(yīng) Java 類型
- response = parseResponse(rawResponse);
- } catch (Throwable e) {
- callFailure(e);
- return;
- }
- callSuccess(response);
- }
- @Override public void onFailure(okhttp3.Call call, IOException e) {
- try {
- callback.onFailure(OkHttpCall.this, e);
- } catch (Throwable t) {
- t.printStackTrace();
- }
- }
- private void callFailure(Throwable e) {
- try {
- callback.onFailure(OkHttpCall.this, e);
- } catch (Throwable t) {
- t.printStackTrace();
- }
- }
- private void callSuccess(Response
response) { - try {
- callback.onResponse(OkHttpCall.this, response);
- } catch (Throwable t) {
- t.printStackTrace();
- }
- }
- });
- }
OkHttp 獲取數(shù)據(jù)后,解析數(shù)據(jù)并回調(diào)callback響應(yīng)的方法,一次網(wǎng)絡(luò)請求便完成了。
總結(jié)
Retrofit 整個框架的代碼不算太多,還是比較易讀的。主要就是通過動態(tài)代理的方式把 Java 接口中的解析為響應(yīng)的網(wǎng)絡(luò)請求,然后交給 OkHttp 去執(zhí)行。并且可以適配不同的 CallAdapter,可以方便與 RxJava 結(jié)合使用。
網(wǎng)站標(biāo)題:Android Retrofit源碼的具體用法解析
文章網(wǎng)址:http://fisionsoft.com.cn/article/dhhsdds.html


咨詢
建站咨詢
