(20)retrofitネットワークフレームワーク面接問題

4129 ワード

一、retrofit使用概要
1.retrofitでhttpリクエストとして1つのインタフェースを介したapiインタフェース
2.Retrofitインスタンスを作成する
3.apiインタフェースを呼び出す
Android Studioに次の依存を追加します.
compile 'com.squareup.retrofit2:retrofit:2.0.1'

ステップ1:apiインタフェースを作成します.
public interface NetApi {
    @GET("repos/{owner}/{repo}/contributors")
    Call contributorsBySimpleGetCall(@Path("owner") String owner, @Path("repo") String repo);
}

注意:@Path注記の内容は@GET注記{}のパラメータに対応しています.
//   :  Retrofit  
Retrofit retrofit = new Retrofit.Builder()
        .baseUrl("https://api.github.com/")
        .build();

//  retrofit           
NetApi repo = retrofit.create(NetApi.class);

//   :               
retrofit2.Call call = repo.contributorsBySimpleGetCall("username", "path");
call.enqueue(new Callback() { //      
    @Override
    public void onResponse(Call call, Response response) {
        //      
    }

    @Override
    public void onFailure(Call call, Throwable t) {
        //        
    }
});

二、retrofitソースコード解析-ダイナミックエージェント
1.まず、methodでServiceMethodに変換します.
2.次に、argsは、serviceMethodを介してokHttpCallオブジェクトを取得する.
3.最後に、さらにokHttpCallをカプセル化してCallオブジェクトに戻します.
retrofitオブジェクトを作成する方法は、次のとおりです.
Retrofit retrofit = new Retrofit.Builder()
        .baseUrl("https://api.github.com/")
        .build();

retrofitオブジェクトを作成する際にbuild()メソッドが使用され、このメソッドの実装は次のようになります.
public Retrofit build() {
  if (baseUrl == null) {
    throw new IllegalStateException("Base URL required.");
  }

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

  Executor callbackExecutor = this.callbackExecutor;
  if (callbackExecutor == null) {
    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); //     Retrofit  
}

メソッドは最後にRetrofitオブジェクトを返します.
retrofitオブジェクトからネットワークリクエストのインタフェースを作成する方法は、次のとおりです.
NetApi repo = retrofit.create(NetApi.class);

ここでretrofitオブジェクトのcreate()メソッドが呼び出されます.このメソッドの実装は次のとおりです.
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.
          if (method.getDeclaringClass() == Object.class) {
            return method.invoke(this, args); //       
          }
          if (platform.isDefaultMethod(method)) {
            return platform.invokeDefaultMethod(method, service, proxy, args); //           
          }
          ServiceMethod serviceMethod = loadServiceMethod(method); //  ServiceMethod  
          OkHttpCall okHttpCall = new OkHttpCall<>(serviceMethod, args); //      okHttpCall  
          return serviceMethod.callAdapter.adapt(okHttpCall); //  okHttpCall
        }
      });
}

まとめ:retrofit最終ネットワークリクエストは依然としてokhttp 3を呼び出す.0で実現します.