Retrofit2使用(一)原理解析

1、获取retrofit           

new Retrofit.Builder()
.baseUrl(url)
.build()

2、获取api接口代理类

   retrofit.create(Class<T> service);

 

 

 

//-----源码解析---------------------

1、使用步骤  

  1. 实例化Retrofit
new Retrofit.Builder()
        .baseUrl()  //---基地址
        .client() //添加自定义 OkHttpClient
        .addConverterFactory()  //---添加转换器工厂  
        .addCallAdapterFactory() //---添加回调适配器   (以上是常用功能 )

        .callbackExecutor()  //--添加网络请求执行Executor
        .callFactory()  // 添加okhttp 中Call.Factory
        .validateEagerly()  //是否一开始就直接缓存网络请求接口里面所有的对应的HttpServiceMethod实例。
        .build();

2、获取api接口 动态代理类,通过动态代理操作 接口类。

 retrofit.create(final Class<T> service)    // --例如  AppHttpApiService  apiService=retrofit.create(AppHttpApiService.class);

3、操作接口访问 数据   ,默认返回类型是 call

 例如:登录     Call call= apiService.login(acc,pwd);

           call.enqueue(new Callback() {
                  @Override
                public void onFailure(Call call, IOException e) {

        }

       @Override
            public void onResponse(Call call, Response response) throws IOException {
          System.out.println("网络响应数据:"+response); 
               }
              });

   

2、原理解析

  •   retrofit 实现了接口与数据的分离,通过动态代理的方式来操作接口。

动态代理涉及到两个类   Proxy和InvocationHandler ,

Proxy.newProxyInstance(ClassLoader loader,Class<?>[] interfaces, InvocationHandler h) 创建代理类,动态代理方法在执行时,会调用h里面的invoke方法去执行


Retrofit中的创建动态代理类。

@SuppressWarnings("unchecked") // Single-interface proxy creation guarded by parameter safety.
public <T> T create(final Class<T> service) {
  validateServiceInterface(service);
  return (T)
      Proxy.newProxyInstance(
          service.getClassLoader(),         //对应接口的 ClassLoader
          new Class<?>[] {service},          // 动态代理类需要实现的接口列表  
          new InvocationHandler() {
            private final Platform platform = Platform.get();
            private final Object[] emptyArgs = new Object[0];

            @Override
            public @Nullable 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);
              }
              args = args != null ? args : emptyArgs;
              return platform.isDefaultMethod(method)
                  ? platform.invokeDefaultMethod(method, service, proxy, args)
                  : loadServiceMethod(method).invoke(args);
            }
          });
}
  •  在执行动态代理方法时会调用invoke   方法,在invoke方法里会执行loadServiceMethod().invoke();

        在 执行loadServiceMethod() 会得到HttpServiceMethod 实体

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

 

  •  在HttpServiceMethod 类里面获取到api接口  注解相关东西 (包括接口里面的方法的返回类型,方法的参数等)
//---这个方法的返回类型是HttpServiceMethod,所以该方法也是得到HttpServiceMethod 的实体的方法

static <ResponseT, ReturnT> HttpServiceMethod<ResponseT, ReturnT> parseAnnotations(
    Retrofit retrofit, Method method, RequestFactory requestFactory) {
  boolean isKotlinSuspendFunction = requestFactory.isKotlinSuspendFunction;
  boolean continuationWantsResponse = false;
  boolean continuationBodyNullable = false;

  Annotation[] annotations = method.getAnnotations();   //--获取该方法的注解
  Type adapterType;    
  if (isKotlinSuspendFunction) {   //--这部分时kotlin相关的
    Type[] parameterTypes = method.getGenericParameterTypes();
    Type responseType =
        Utils.getParameterLowerBound(
            0, (ParameterizedType) parameterTypes[parameterTypes.length - 1]);
    if (getRawType(responseType) == Response.class && responseType instanceof ParameterizedType) {
      // Unwrap the actual body type from Response<T>.
      responseType = Utils.getParameterUpperBound(0, (ParameterizedType) responseType);
      continuationWantsResponse = true;
    } else {
      // TODO figure out if type is nullable or not
      // Metadata metadata = method.getDeclaringClass().getAnnotation(Metadata.class)
      // Find the entry for method
      // Determine if return type is nullable or not
    }

    adapterType = new Utils.ParameterizedTypeImpl(null, Call.class, responseType);
    annotations = SkipCallbackExecutorImpl.ensurePresent(annotations);
  } else {
    adapterType = method.getGenericReturnType();   //获取方法的返回类型
  }

  CallAdapter<ResponseT, ReturnT> callAdapter =
      createCallAdapter(retrofit, method, adapterType, annotations);   //这里时选择回调适配器 ,如果添加了rxjava适配器,并且方法返回类型是Observable,那么这里选择的适配器就为rxjava 适配器
  Type responseType = callAdapter.responseType();
  if (responseType == okhttp3.Response.class) {
    throw methodError(
        method,
        "'"
            + getRawType(responseType).getName()
            + "' is not a valid response body type. Did you mean ResponseBody?");
  }
  if (responseType == Response.class) {
    throw methodError(method, "Response must include generic type (e.g., Response<String>)");
  }
  // TODO support Unit for Kotlin?
  if (requestFactory.httpMethod.equals("HEAD") && !Void.class.equals(responseType)) {
    throw methodError(method, "HEAD method must use Void as response type.");
  }

  Converter<ResponseBody, ResponseT> responseConverter =
      createResponseConverter(retrofit, method, responseType);      //--这里获取响应数据转换器 --如果添加了 json转换器, responseType 为json类型,那么转换器就为json,响应的结果就为自动转换为json格式

  okhttp3.Call.Factory callFactory = retrofit.callFactory;
  if (!isKotlinSuspendFunction) {
    return new CallAdapted<>(requestFactory, callFactory, responseConverter, callAdapter);    //--返回HttpServiceMethod 实体
  } else if (continuationWantsResponse) {
    //noinspection unchecked Kotlin compiler guarantees ReturnT to be Object.
    return (HttpServiceMethod<ResponseT, ReturnT>)   //--返回HttpServiceMethod 实体
        new SuspendForResponse<>(
            requestFactory,
            callFactory,
            responseConverter,
            (CallAdapter<ResponseT, Call<ResponseT>>) callAdapter);
  } else {
    //noinspection unchecked Kotlin compiler guarantees ReturnT to be Object.
    return (HttpServiceMethod<ResponseT, ReturnT>)   //--返回HttpServiceMethod 实体
        new SuspendForBody<>(
            requestFactory,
            callFactory,
            responseConverter,
            (CallAdapter<ResponseT, Call<ResponseT>>) callAdapter,
            continuationBodyNullable);
  }
}
  •  在动态代理的invoke 方法里面还执行了HttpServiceMethod 中invoke方法

    

@Override
final @Nullable ReturnT invoke(Object[] args) {
  Call<ResponseT> call = new OkHttpCall<>(requestFactory, args, callFactory, responseConverter);   //-- 网络请求
  return adapt(call, args);          //-- 根据回调适配器,执行回调功能(例如rxJava, 这里就会将返回的call 转换为Obsrvable)
}
  • OkHttpCall 就是okhttp 的网络请求相关的代码
@Override
public void enqueue(final Callback<T> callback) {
  Objects.requireNonNull(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) {
            throwIfFatal(t);
            t.printStackTrace(); // TODO this is not great
          }
        }

        @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) {
            throwIfFatal(t);
            t.printStackTrace(); // TODO this is not great
          }
        }
      });
}
  • adapt(call, args)是回调适配器 callAdapter的方法,例如如果回调适配器是RxJava3CallAdapter
@Override
public Object adapt(Call<R> call) {
  Observable<Response<R>> responseObservable =
      isAsync ? new CallEnqueueObservable<>(call) : new CallExecuteObservable<>(call);   //根据是异步 和同步来判断执行哪个方法

  Observable<?> observable;
  if (isResult) {
    observable = new ResultObservable<>(responseObservable);
  } else if (isBody) {
    observable = new BodyObservable<>(responseObservable);
  } else {
    observable = responseObservable;
  }

  if (scheduler != null) {
    observable = observable.subscribeOn(scheduler);
  }

  if (isFlowable) {
    return observable.toFlowable(BackpressureStrategy.LATEST);
  }
  if (isSingle) {
    return observable.singleOrError();
  }
  if (isMaybe) {
    return observable.singleElement();
  }
  if (isCompletable) {
    return observable.ignoreElements();
  }
  return RxJavaPlugins.onAssembly(observable);
}

 

final class CallEnqueueObservable<T> extends Observable<Response<T>> {
  private final Call<T> originalCall;

  CallEnqueueObservable(Call<T> originalCall) {
    this.originalCall = originalCall;
  }

  @Override
  protected void subscribeActual(Observer<? super Response<T>> observer) {
    // Since Call is a one-shot type, clone it for each new observer.
    Call<T> call = originalCall.clone();
    CallCallback<T> callback = new CallCallback<>(call, observer);    
    observer.onSubscribe(callback);
    if (!callback.isDisposed()) {
      call.enqueue(callback);      //执行网络访问
    }
  }

 

3、关键类说明


 

1、HttpServiceMethod 类    : 每一个接口方法都一个HttpServiceMethod ,它是接口方法的具体实现。

   作用;

         1、获取接口的返回类型,参数,回调适配器,转换适配器等等

         2、网络数据请求

            invoke(Object[] args) 方法执行Call<ResponseT> call = new OkHttpCall<>(requestFactory, args, callFactory, responseConverter); 得到call

2、OkHttpCall  类:数据请求  关键方法enqueue()和execute();

  

 

3、retrofit  类:网络数据访问调度类,整个框架的起点。

  方法    ServiceMethod<?> loadServiceMethod(Method method)  —>parseAnnotations()——>解析注解(HttpServiceMethod)

 

4、其他说明

1、注解  :定义了方法,和网络请求参数 ,

2、动态代理   :得到注解类的代理     ,在代理类里面加载 loadServiceMethod(method)——>得到HttpServiceMethod 并且执行HttpServiceMethod.invoke()方法

3、反射

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值