广告
返回顶部
首页 > 资讯 > 移动开发 >Android开发Retrofit源码分析
  • 346
分享到

Android开发Retrofit源码分析

2024-04-02 19:04:59 346人浏览 八月长安
摘要

目录项目结构retrofit 使用Retrofit #createServiceMethod #parseAnnotationshttpserviceMethod#parseAnno

项目结构

源码 clone 下来 , 可以看到 retrofit 整体结构如下

Http包目录下就是一些http协议常用接口 , 比如 请求方法 url , 请求体, 请求行 之类的

retrofit 使用

把retrofit使用作为分析的切入口吧 , retrofit单元测试使用如下

public final class BasicCallTest {
    @Rule public final MockWEBServer server = new MockWebServer();
    interface Service {
        @GET("/") Call<ResponseBody> getBody();
    }
    @Test public void responseBody() throws IOException {
        Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(server.url("/"))
            .build();
        Service example = retrofit.create(Service.class);
        server.enqueue(new MockResponse().setBody("1234"));
        Response<ResponseBody> response = example.getBody().execute();
        assertEquals("1234", response.body().string());
    }
}

Retrofit 构建 , 以构建者模式构建出Retrofit

可以看到builer可以配置baseUrl , 回调线程池 , 还有一些适配器的工厂 , 这些适配器的作用后面说

Retrofit #create

从create 方法开始分析 , 跟进看下create 方法

public <T> T create(final Class<T> service) {
    validateServiceInterface(service);
    return (T)
        Proxy.newProxyInstance(
        service.getClassLoader(),
        new Class<?>[] {service},
        new InvocationHandler() {
            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;
                Platform platform = Platform.get();
                return platform.isDefaultMethod(method)
                    ? platform.invokeDefaultMethod(method, service, proxy, args)
                    : loadServiceMethod(method).invoke(args);
            }
        });
}

service 是请求的接口的class , 动态代理只能是接口 , 所以validateServiceInterface 先验证是不是接口 , 不是接口则抛异常。

method.getDeclaringClass() 获取声明类的Class。

比如 A类 有个method , method.getDeclaringClass() 返回为A.class , 如果method声明类是Object.class 则直接method.invoke , 往下执行毫无意义。

Platform#get()会根据当前平台获取Platform 。

有点类似状态模式思想 , 根据当前的平台选择合适的子类

public boolean isDefaultMethod(Method method) {
    return method.isDefault();
    }

isDefault , 在接口类型中以default关键字声明 则返回true, 比如

interface InterfaceWithDefault {
    void firstMethod();
    default void newMethod() {
        System.out.println("newMethod");
    }
}

所以此处会返回 false 接着调用 loadServiceMethod。

ServiceMethod #parseAnnotations

跟进ServiceMethod #parseAnnotations

  static <T> ServiceMethod<T> parseAnnotations(Retrofit retrofit, Method method) {
    RequestFactory requestFactory = RequestFactory.parseAnnotations(retrofit, method);
    return HttpServiceMethod.parseAnnotations(retrofit, method, requestFactory);
  }

根据当前的方法信息构建出RequestFactory , 然后把具体实现细节交给HttpServiceMethod 处理 , HttpServiceMethod 继承自ServiceMethod , 有三个子类 。

我们在api.class定义的方法 , 解析并不是由HttpServiceMethod 完成 , 而是由RequestFactory去处理的 , 比如解析方法的注解。

更多的解析方法如下

方法解析的细节就不说了 , 继续看RequestFactory 这个类 , 这个类的作用难道就是负责方法信息的解析 , 感觉和名字不太符合 , RequestFactory 顾名思义应该是用来构建Request的工厂 , 果不其然内部还有个 create 方法 , 用来构建okhttp3.Request的

  //RequestFactory #create
okhttp3.Request create(Object[] args) throws IOException {
    return requestBuilder.get().tag(Invocation.class, new Invocation(method, argumentList)).build();
  }

就只有这一个create方法 , 难道retrofit 就只能使用okhttp来负责网络请求 ? 答案是肯定的 , 从最开始的 loadServiceMethod(method).invoke(args)也可以看出 , 方法里面只构建出OkHttpCall 没提供api可以让我们切换到其他的网络请求库。

但是 , Call 又抽象成接口的形式 ,如下, 这么做的目的可能是以后便于框架的维护

沿途风景再美丽 , 也要回到主线路 , 继续分析 HttpServiceMethod#parseAnnotations

HttpServiceMethod#parseAnnotations

这个方法太长 , 贴关键代码吧

 static <ResponseT, ReturnT> HttpServiceMethod<ResponseT, ReturnT> parseAnnotations(
      Retrofit retrofit, Method method, RequestFactory requestFactory) {
    boolean isKotlinSuspendFunction = requestFactory.isKotlinSuspendFunction;
    boolean continuationWantsResponse = false;
    boolean continuationBodyNullable = false;
    boolean continuationIsUnit = false;
    Annotation[] annotations = method.getAnnotations();
    Type adapterType;
    if (isKotlinSuspendFunction) {
      Type[] parameterTypes = method.getGenericParameterTypes();
      Type responseType =
          Utils.getParameterLowerBound(
              0, (ParameterizedType) parameterTypes[parameterTypes.length - 1]);
      if (getRawType(responseType) == Response.class && responseType instanceof ParameterizedType) {
        continuationWantsResponse = true;
      }
    } else {
      //非kt 协程情况
      adapterType = method.getGenericReturnType();
    }
    CallAdapter<ResponseT, ReturnT> callAdapter =
        createCallAdapter(retrofit, method, adapterType, annotations);
    Type responseType = callAdapter.responseType();
    Converter<ResponseBody, ResponseT> responseConverter =
        createResponseConverter(retrofit, method, responseType);
    okhttp3.Call.Factory callFactory = retrofit.callFactory;
    if (!isKotlinSuspendFunction) {
        //非kt 协程情况
      return new CallAdapted<>(requestFactory, callFactory, responseConverter, callAdapter);
    } else if (continuationWantsResponse) {
      return (HttpServiceMethod<ResponseT, ReturnT>)
          new SuspendForResponse<>(
              requestFactory,
              callFactory,
              responseConverter,
              (CallAdapter<ResponseT, Call<ResponseT>>) callAdapter);
    } else {
      return (HttpServiceMethod<ResponseT, ReturnT>)
          new SuspendForBody<>(
              requestFactory,
              callFactory,
              responseConverter,
              (CallAdapter<ResponseT, Call<ResponseT>>) callAdapter,
              continuationBodyNullable,
              continuationIsUnit);
    }
  }

构建出HttpServiceMethod分两种情况 :

  • kotlin 协程情况
  • 非Kotlin 协程情况

第二种 非Kotlin协程情况

第一种情况稍许复杂 , 先分析第二种

adapterType = method.getGenericReturnType();

 @GET("/") Call<ResponseBody> getBody();

如果是上面代码 , method.getGenericReturnType() = Call , 然后根据方法的返回值类型 / 方法注解信息 , 构建出CallAdapter 。

createCallAdapter() 方法会使用 CallAdapter.Factory 构建CallAdapter , 因为初始化retrofit的时候没有配置CallAdapter.Factory , 所以会使用默认的DefaultCallAdapterFactory。

最终会进入DefaultCallAdapterFactory#get 。

DefaultCallAdapterFactory#get

这个方法作用就是返回CallAdapter , 修改下源码加入两个打印。

  public @Nullable CallAdapter<?, ?> get(
      Type returnType, Annotation[] annotations, Retrofit retrofit) {
    final Type responseType = Utils.getParameterUpperBound(0, (ParameterizedType) returnType);
    System.out.println("TAG" + " ->" + "returnType = " +getRawType(returnType) .getSimpleName());
    System.out.println("TAG" + " ->" + "responseType = " +getRawType(responseType) .getSimpleName());
    return new CallAdapter<Object, Call<?>>() {
      @Override
      public Type responseType() {
        return responseType;
      }
      @Override
      public Call<Object> adapt(Call<Object> call) {
        return executor == null ? call : new ExecutorCallbackCall<>(executor, call);
      }
    };
  }

运行可以看到以下打印信息

returnType = Call ,responseType =ResponseBody 。

总结一下 , returnType就是方法返回值 , responseType 就是方法返回值上的泛型 DefaultCallAdapterFactory会根据平台环境去构建。

Android24分析 , DefaultCallAdapterFactory(Executor callbackExecutor) , 构造方法中 , 线程池为主线程池 , 在retrofit初始化的时候添加到 到callAdapterFactories 集合中。

至此 , CallAdapterFactory 和 CallAdapter 分析完了 , 总结下就是给Call (retrofit内存只有OkHttpCall 作为唯一实现类)做适配 , 让其可以在 Rxjava / 协程 等各个环境中使用 Call。

非kt 协程情况下 , parseAnnotations 方法最终返回的是将requestFactory , callFactory , responseConverter, callAdapter 封装好的CallAdapted 对象。

再次回到梦开始的地方Retrofit#create 方法 , loadServiceMethod获取的ServiceMethod最终实现类为CallAdapted , 获取之后会调用invoke方法 , invoke是一个final方法 , 里面构建了OkHttpCall , 然后调用了adapt方法 , adapt中调用了callAdapter.adapt(call)。

   @Override
    protected ReturnT adapt(Call&lt;ResponseT&gt; call, Object[] args) {
      return callAdapter.adapt(call);
    }

这里的ReturnT 就是ExecutorCallbackCall<>(executor, call) 对象 , 所以 example.getBody().execute() 就是调用ExecutorCallbackCall#execute方法

 //ExecutorCallbackCall#execute
 public Response<T> execute() throws IOException {
      return delegate.execute();
    }

delegate为OkHttpCall , 所以就调用到OkHttpCallCall#execute方法 , 这里就转给Okhttp去请求网络加载数据了 , 代码就不贴了 , 我们看下网络请求之后 , 数据Response 的处理 , 关键代码OkHttpCall#parseResponse。

 Response<T> parseResponse(okhttp3.Response rawResponse) throws IOException {
    ResponseBody rawBody = rawResponse.body();
    ExceptionCatchingResponseBody catchingBody = new ExceptionCatchingResponseBody(rawBody);
    try {
      T body = responseConverter.convert(catchingBody);
      return Response.success(body, rawResponse);
    } 
  }

responseConverter 在 HttpServiceMethod#parseAnnotations 方法中获取 , 回应数据转换器 , 把数据转换成我们可以直接使用的对象 , 比如我们常用的 GsonConverterFactory。

最后把转换好之后的数据 , 封装成Response对象返回。

response.body()就是responseConverter 转换后的数据 来张大致流程图感受下吧

第一种 Kotlin协程情况

其实大致流程第二种情况分析的差不多了 , 接下来分析下Retrofit对于kotlin的特殊处理吧。

 if (Utils.getRawType(parameterType) == Continuation.class) {
              isKotlinSuspendFunction = true;
              return null;
            }

协程挂起方法 , 第一个参数为Continuation , 所以判断是不是挂起方法也很简单 , 根据ResponseType 去构建协程专用的HttpServiceMethod , 主要有两类。

  • SuspendForResponse , 对应type为Continuation<Response>
  • SuspendForBody , 对应type为Continuation

这里看下 SuspendForBody 实现 , 套娃情况就不分析了。

如果是这样使用 , 最终会调到SuspendForBody #adapt。

 @Override
    protected Object adapt(Call<ResponseT> call, Object[] args) {
      call = callAdapter.adapt(call);
      Continuation<ResponseT> continuation = (Continuation<ResponseT>) args[args.length - 1];
      try {
         //去掉干扰代码 , 仅保留这个
          return KotlinExtensions.awaitNullable(call, continuation);
      }
    }

这个地方就很关键了 , java 直接调kotlin 协程 suspend 方法。

KotlinExtensions.awaitNullable 会调到KotlinExtensions#await方法。

retrofit与协程适配的细节都在 KotlinExtensions这个类里。

进入await , 可以看到使用suspendCancellableCoroutine把回调装换成协程。

@JVMName("awaitNullable")
suspend fun <T : Any> Call<T?>.await(): T? {
    return suspendCancellableCoroutine { continuation ->
        continuation.invokeOnCancellation {
            cancel()
        }
        enqueue(object : Callback<T?> {
            override fun onResponse(call: Call<T?>, response: Response<T?>) {
                if (response.isSuccessful) {
                    continuation.resume(response.body())
                } else {
                    continuation.resumeWithException(HttpException(response))
                }
            }
            override fun onFailure(call: Call<T?>, t: Throwable) {
                continuation.resumeWithException(t)
            }
        })
    }
}

其实内部也是调用 OkHttp Call.enqueue() , 只不过是用suspendCancellableCoroutine给协程做了一层包装处理

通过 suspendCancellableCoroutine包装之后使用就很简单了。

 GlobalScope.launch {
            try {
                val result = xxxApi.getXxx()
            } catch (exception: Exception) {
            }
        }

总结

Call 这个接口用于与网络请求库做适配 , 比如Okhttp。

CallAdapter 用于retrofit 与各种环境搭配使用做适配 , 比如rxjava / 协程 / java。

Converter 用于将请求结果转换实体类Bean 或者其他。

用到的设计模式有: 动态代理/静态代理 / 构建者 / 工厂 / 适配器 / 状态 等。

以上就是Android开发Retrofit源码分析的详细内容,更多关于Android Retrofit源码分析的资料请关注编程网其它相关文章!

--结束END--

本文标题: Android开发Retrofit源码分析

本文链接: https://www.lsjlt.com/news/165430.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作