Retrofit2 原理解析

Retrofit是什麼

官網介紹是A type-safe HTTP client for Android and Java,是一個 RESTful 的 HTTP 網絡請求框架的封裝,但網絡請求不是Retrofit來完成的,它只是封裝了請求參數、Header、Url、返回結果處理等信息,而請求是由OkHttp3來完成的。html

入門

Retrofit入門很是簡單,首先須要在build.gradle引用相關依賴java

implementation 'com.squareup.retrofit2:retrofit:2.5.0'

定義一個HTTP API接口類git

public interface GitHubService {
  @GET("users/{user}/repos")
  Call<List<Repo>> listRepos(@Path("user") String user);
}

使用Retrofit類生成GitHubService 接口實現github

Retrofit retrofit = new Retrofit.Builder()
    .baseUrl("https://api.github.com/")
    .build();

GitHubService service = retrofit.create(GitHubService.class);

發送HTTP請求,返回Response能夠同步或者異步處理api

Call<List<Repo>> repos = service.listRepos("octocat");
// 同步
List<Repo> data = repos.execute(); 
// 異步
repos.enqueue(new Callback<List<Repo>>() {
            @Override
            public void onResponse(Call<List<Repo>> call, Response<List<Repo>> response) {
                List<Repo> data = response.body();
            }

            @Override
            public void onFailure(Call<List<Repo>> call, Throwable t) {
                t.printStackTrace();
            }
        });

Retrofit入門就是這幾步,固然在實際使用的時候確定沒有那麼簡單,能夠根據具體需求來處理,以前寫過一篇文章Retrofit+Rxjava的封裝,具體能夠去看看。緩存

解讀

Retrofit庫有四個module,包含retrofit,adapter,convert,mock等,咱們先來看看Retrofit總體結構,先對它有個大致的瞭解。
安全

  • 請求方法

Retrofit定義了請求註解類,支持請求方法包含GET、POST、HEAD、OPTIONS、PUT、DELETE、PATCH請求,固然你也能夠直接使用HTTP自定義請求。例如以GET請求爲例,服務器

@Documented
@Target(METHOD)
@Retention(RUNTIME)
public @interface GET {
  /**
   * A relative or absolute path, or full URL of the endpoint. This value is optional if the first
   * parameter of the method is annotated with {@link Url @Url}.
   * <p>
   * See {@linkplain retrofit2.Retrofit.Builder#baseUrl(HttpUrl) base URL} for details of how
   * this is resolved against a base URL to create the full endpoint URL.
   */
  String value() default "";
}

GET定義了一個value,這個值是相關請求的path,而咱們在建立Retrofit的時候已經傳入一個baseUrl,這兩個會組裝成真正的請求url。若是想使用HTTP自定義,能夠這樣定義:網絡

HTTP(method = "DELETE", path = "remove/", hasBody = true)
  • 請求參數

Retrofit定義了請求參數註解類,包含Body、Field、FieldMap、Header、HeaderMap、Part、PartMap、Query、QueryMap、QueryName。以Query爲例,例如 http://api.github.com/list?page=10,能夠寫成下面的代碼。框架

@GET("/list")
Call<ResponseBody> list(@Query("page") int page);

使用POST的時候,絕大多數的服務端接口都須要作加密、鑑權和校驗,能夠使用@Field來處理參數

@POST("/list")
Call<ResponseBody> list(@Field("page") int page);

而Map結尾的註解參數類,其實就是數據集,如@QueryMap Map<String, String> map

  • Converter

在Retrofit中,不管是發送數據和接收數據,都是經過OKHttp的RequestBody和ResponseBody來實現的。在實際項目中,有時候原始的RequestBody或是ResponseBody並不能知足咱們的需求(如接口加密),就須要對它進行轉換。並且Retrofit官方給瞭如下幾個經常使用的轉換庫。

  • Gson: com.squareup.retrofit2:converter-gson
  • Jackson: com.squareup.retrofit2:converter-jackson
  • Moshi: com.squareup.retrofit2:converter-moshi
  • Protobuf: com.squareup.retrofit2:converter-protobuf
  • Wire: com.squareup.retrofit2:converter-wire
  • Simple XML: com.squareup.retrofit2:converter-simplexml
  • Scalars (primitives, boxed, and String): com.squareup.retrofit2:converter-scalars

這對於通常的使用來講確實夠用了,可是若是咱們對安全性要求比較高,或者編碼不太同樣的話,這些庫就無法使用了,因而咱們就須要自定義ConverterFactory。Retrofit已經爲咱們提供了自定義Converter.Factory的接口,咱們只須要實現它給的接口便可。

public final class ProtoConverterFactoryCompat extends Converter.Factory {
    public static ProtoConverterFactoryCompat create() {
        return new ProtoConverterFactoryCompat(null);
    }

    /**
     * Create an instance which uses {@code registry} when deserializing.
     */
    public static ProtoConverterFactoryCompat createWithRegistry(ExtensionRegistryLite registry) {
        return new ProtoConverterFactoryCompat(registry);
    }

    private final ExtensionRegistryLite registry;

    private ProtoConverterFactoryCompat(ExtensionRegistryLite registry) {
        this.registry = registry;
    }

    @Override
    public Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations,
                                                            Retrofit retrofit) {
        if (!(type instanceof Class<?>)) {
            return null;
        }
        Class<?> c = (Class<?>) type;
        if (!MessageLite.class.isAssignableFrom(c)) {
            return null;
        }

        Parser<MessageLite> parser = null;
        try {
            parser = ProtoJavas.getParser(c);
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        if (parser == null)
            throw new IllegalArgumentException(
                    "Found a protobuf message but " + c.getName() + " had no PARSER field.");

        return new ProtoResponseBodyConverterCompat<>(parser, registry);
    }

    @Override
    public Converter<?, RequestBody> requestBodyConverter(Type type,
                                                          Annotation[] parameterAnnotations, Annotation[] methodAnnotations, Retrofit retrofit) {
        if (!(type instanceof Class<?>)) {
            return null;
        }
        if (!MessageLite.class.isAssignableFrom((Class<?>) type)) {
            return null;
        }
        return new ProtoRequestBodyConverterCompat<>();
    }

原理

  • 初始化

Retrofit採用了Builder模式,進行了一系列的初始化操做,在build裏面把咱們初始化傳入的參數進行整合,返回給咱們一個Retrofit對象。

public Retrofit build() {
  if (baseUrl == null) {
    throw new IllegalStateException("Base URL required.");
  }

  okhttp3.Call.Factory callFactory = this.callFactory;
  if (callFactory == null) {
    callFactory = new OkHttpClient();
  }

  Executor callbackExecutor = this.callbackExecutor;
  if (callbackExecutor == null) {
    callbackExecutor = platform.defaultCallbackExecutor();
  }

  // Make a defensive copy of the adapters and add the default Call adapter.
  List<CallAdapter.Factory> callAdapterFactories = new ArrayList<>(this.callAdapterFactories);
  callAdapterFactories.addAll(platform.defaultCallAdapterFactories(callbackExecutor));

  // Make a defensive copy of the converters.
  List<Converter.Factory> converterFactories = new ArrayList<>(
      1 + this.converterFactories.size() + platform.defaultConverterFactoriesSize());

  // Add the built-in converter factory first. This prevents overriding its behavior but also
  // ensures correct behavior when using converters that consume all types.
  converterFactories.add(new BuiltInConverters());
  converterFactories.addAll(this.converterFactories);
  converterFactories.addAll(platform.defaultConverterFactories());

  return new Retrofit(callFactory, baseUrl, unmodifiableList(converterFactories),
      unmodifiableList(callAdapterFactories), callbackExecutor, validateEagerly);
}

這裏面咱們主要看下面這個幾個參數。

  • callFactory對okhttp的自定義,好比攔截器公共參數的設置等
  • callbackExecutor 可不設置,會根據平臺來建立默認的
  • converterFactories存儲對轉換的支持,在咱們請求服務器數據是返回的時候自動解析成咱們須要的bean類型
  • callAdapterFactories 添加適配器支持,可設置Rxjava的支持
  • 接口類

前面已經說了如何使用retrofit,首先建立了一個server接口,使用的時候確定不是接口實現的,但它是如何使用的呢?其實retrofit使用了動態代理來實現的。下面看看它的源碼

public <T> T create(final Class<T> 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();
        private final Object[] emptyArgs = new Object[0];

        @Override public Object invoke(Object proxy, Method method, @Nullable Object[] args)
            throws Throwable {
          // If the method is a method from Object then defer to normal invocation.
          if (method.getDeclaringClass() == Object.class) {
            return method.invoke(this, args);
          }
          if (platform.isDefaultMethod(method)) {
            return platform.invokeDefaultMethod(method, service, proxy, args);
          }
          return loadServiceMethod(method).invoke(args != null ? args : emptyArgs);
        }
      });
}

ServiceMethod<?> loadServiceMethod(Method method) {
  ServiceMethod<?> result = serviceMethodCache.get(method);
  if (result != null) return result;

  synchronized (serviceMethodCache) {
    result = serviceMethodCache.get(method);
    if (result == null) {
      result = ServiceMethod.parseAnnotations(this, method);
      serviceMethodCache.put(method, result);
    }
  }
  return result;
}

ServiceMethod中保存方法緩存,若是沒有就新建立而後添加到緩存裏,而且這裏返回的是一個動態代理InvocationHandler。

  • 請求處理

Retrofit 經過invoke爲咱們構造了一個 OkHttpCall ,實際上每個 OkHttpCall 都對應於一個請求,它主要完成最基礎的網絡請求,而咱們在接口的返回中看到的 Call 默認狀況下就是 OkHttpCall 了,若是咱們添加了自定義的 callAdapter,那麼它就會將 OkHttp 適配成咱們須要的返回值,並返回給咱們。

@Override ReturnT invoke(Object[] args) {
  return callAdapter.adapt(
      new OkHttpCall<>(requestFactory, args, callFactory, responseConverter));
}

最後經過OkHttpCall.execute發起網絡請求

@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 {
        call = rawCall = createRawCall();
      } catch (Throwable t) {
        throwIfFatal(t);
        failure = creationFailure = t;
      }
    }
  }

  if (failure != null) {
    callback.onFailure(this, failure);
    return;
  }

  if (canceled) {
    call.cancel();
  }

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

看到 OkHttpCall 其實也是封裝了 okhttp3.Call,在這個方法中,咱們經過 okhttp3.Call 發起了請求。而parseResponse 主要完成了由 okhttp3.Response 向 retrofit.Response 的轉換,同時也處理了對原始返回的解析。

總結

  • Retrofit經過動態代理,用MethodHandler完成接口方法。
  • Retrofit的MethodHandler經過RequestFactoryParser.parse解析,得到接口方法的參數和註解的值,傳入到OkHttpCall,OkHttpCall生成okhttp3.Call完成Http請求並使用Converter解析數據回調。
  • Retrofit經過工廠設置CallAdapter和Converter,CallAdapter包裝轉換Call,Converter轉換(解析)服務器返回的數據、接口方法的註解參數。
相關文章
相關標籤/搜索