Android Retrofit原理

本文详细剖析了Retrofit在创建网络请求时的内部流程,包括通过动态代理生成服务接口实例,利用注解解析生成OKHttp相关参数,并重点讲解了ServiceMethod的缓存机制,确保高效重复使用解析结果。同时,附带流程图帮助读者直观理解。
摘要由CSDN通过智能技术生成

有兴趣的同学可以参考下面的流程,阅读Retrofit代码。

下面是retrofit进行网络请求的具体流程:

1.在retrofit.creat()中,return的时候会去创建一个动态代理类,具体代码如下:

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

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

            //loadServiceMethod会去根据动态代理的method方法上面的注解去动态生成OKHttp的相关参数
            ServiceMethod serviceMethod = loadServiceMethod(method);
            OkHttpCall okHttpCall = new OkHttpCall<>(serviceMethod, args);
            return serviceMethod.callAdapter.adapt(okHttpCall);
          }
        });
  }

2.loadServiceMethod会去根据动态代理的method方法上面的注解去动态生成OKHttp的相关参数,具体代码大家可以跳转到ServiceMethod类中看一下。这里有个重要的点是,只有第一次解析的时候会为method去解析注解数据并缓存到map中,后面再去调用都会去使用map中的ServiceMethod对象。

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

3. 看下面流程图吧

一图胜万言,上图吧:

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值