Retrofit源码分析之一

本文深入剖析了Retrofit网络请求的实现原理,包括其与OkHttp的协作机制、动态代理的使用、接口注解的解析过程及源码分析。特别关注了Retrofit在Android平台上的默认行为。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Retrofit 请求网络

实际上是使用 Retrofit 接口层封装请求参数、Header、Url 等信息,之后由 OkHttp完成后续的请求操作,在服务端返回数据之后,OkHttp 将原始的结果交给 Retrofit,后者根据用户的需求对结果进行解析的过程。Retrofit的大概原理过程如下:

  1. Retrofit 将 Http请求 抽象 成 Java接口
  2. 在接口里用 注解 描述和配置 网络请求参数
  3. 用动态代理 的方式,动态将网络请求接口的注解 解析 成HTTP请求
  4. 最后执行HTTP请求

先看调用方式:

1、Retrofit之kotlin使用方式

  1. 1、创建一个api服务管理类
/**
 * Api管理工具类,通过该类创建相应的api-service类
 */
object ApiServiceManager {

    private val gson = GsonBuilder().registerTypeAdapter(Date::class.java, JsonDeserializer<Date> { json, _, _ -> Date(json.asJsonPrimitive.asLong) }).create()

    private val mRetrofit: Retrofit = Retrofit.Builder()
            .baseUrl(RequestDomainConfig.getRequestDefault())
            .client(HttpClientManager.mOkHttpClient)//OKHTTP网络请求
            .addConverterFactory(GsonConverterFactory.create(gson))//添加json解析器
            .addCallAdapterFactory(RxJava2CallAdapterFactory.create())//添加RxJava转换器
            .build()

    fun <T> create(service: Class<T>): T = mRetrofit.create(service)
}
  1. 2、创建一个服务接口类,供retrofit解析注解
interface ApiUserService {
  
    //用户登录
    @POST("userAuth.login")
    fun loginByAccount(@Body httpRequest: HttpRequest): Observable<UserInfoVo>
  1. 3、创建接口调用类(真正调用接口)
object ApiUser {
    private val sService = ApiServiceManager.create(ApiUserService::class.java)


 /**
     * 用户登录
     */
    fun <E> loginByAccount(rxObserver: RxObserver<UserInfoVo>, mView: LifecycleProvider<E>,             account: String, password: String) {
        sService.loginByAccount(HttpRequest.obtainHttpRequest(HttpEntry("account",account),
                HttpEntry("pwd", password)))//请求参数
                .compose(RxHelper.handleSingleResult())//封装RXJava返回值的解析
                .bindToLifecycle(mView)//绑定生命周期
                .subscribe(rxObserver)
    }
}

2、retrofit类源码分析

先看构造函数和成员变量

public final class Retrofit {
  private final Map<Method, ServiceMethod<?>> serviceMethodCache = new ConcurrentHashMap<>();

  final okhttp3.Call.Factory callFactory;// 生产网络请求器(Call)的工厂,默认使用OkHttp
  final HttpUrl baseUrl;// url地址
  final List<Converter.Factory> converterFactories;// 数据转换器(converter)工厂
  final List<CallAdapter.Factory> callAdapterFactories;// 生产网络请求适配器(CallAdapter)的工厂List
  final @Nullable Executor callbackExecutor;// 回调方法执行器
  final boolean validateEagerly; // 是否提前对业务接口中的注解进行验证转换的标志位

  Retrofit(okhttp3.Call.Factory callFactory, HttpUrl baseUrl,
      List<Converter.Factory> converterFactories, List<CallAdapter.Factory> callAdapterFactories,
      @Nullable Executor callbackExecutor, boolean validateEagerly) {
    this.callFactory = callFactory;
    this.baseUrl = baseUrl;
    this.converterFactories = converterFactories; // Copy+unmodifiable at call site.
    this.callAdapterFactories = callAdapterFactories; // Copy+unmodifiable at call site.
    this.callbackExecutor = callbackExecutor;
    this.validateEagerly = validateEagerly;
  }

  Retrofit.Builder  静态内部类

 public static final class Builder {
    private final Platform platform;
    private @Nullable okhttp3.Call.Factory callFactory;
    private @Nullable HttpUrl baseUrl;
    private final List<Converter.Factory> converterFactories = new ArrayList<>();
    private final List<CallAdapter.Factory> callAdapterFactories = new ArrayList<>();
    private @Nullable Executor callbackExecutor;
    private boolean validateEagerly;

    Builder(Platform platform) {
      this.platform = platform;
    }

    public Builder() {
      this(Platform.get()); // Retrofit支持Android Java8 默认Platform 三种平台,此处确认当前是在哪个平台环境运行
    }

    Builder(Retrofit retrofit) {
      platform = Platform.get();
      callFactory = retrofit.callFactory;
      baseUrl = retrofit.baseUrl;
        
      ****省略代码
     }
}

retrofit是通过builder()方法来创建的,再看builder()方法:

 public Retrofit build() {
      //请求地址不可空
      if (baseUrl == null) {
        throw new IllegalStateException("Base URL required.");
      }

      //默认为OKHTTP
      okhttp3.Call.Factory callFactory = this.callFactory;
      if (callFactory == null) {
        callFactory = new OkHttpClient();
      }

      Executor callbackExecutor = this.callbackExecutor;
      if (callbackExecutor == null) {
        callbackExecutor = platform.defaultCallbackExecutor();
      }
        
      ***省略代码
}

最后看create方法:关于动态代理的使用可以看看这篇文章https://blog.youkuaiyun.com/yaomingyang/article/details/80981004

  public <T> T create(final Class<T> service) {
    //校验是否为接口,且不能继承其他接口
    Utils.validateServiceInterface(service);
     // 是否需要提前解析接口方法
    if (validateEagerly) {
      eagerlyValidateMethods(service);
    }
    //动态代理,返回一个 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 @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);
            }
            if (platform.isDefaultMethod(method)) {
              return platform.invokeDefaultMethod(method, service, proxy, args);
            }
            return loadServiceMethod(method).invoke(args != null ? args : emptyArgs);
          }
        });
  }

3、Platform类解析,用来支持java8版本之下的java平台。

class Platform {
    ...
    // 无回调执行器,在哪里创建的,就在哪里回调
  Executor defaultCallbackExecutor() {
    return null;
  }
  // 平台默认的回调适配器工厂列表为new DefaultCallAdapterFactory(callbackExecutor)
  List<? extends CallAdapter.Factory> defaultCallAdapterFactories(
      @Nullable Executor callbackExecutor) {
    return singletonList(new DefaultCallAdapterFactory(callbackExecutor));
  }
  // 默认回调适配器工厂数量为1
    int defaultCallAdapterFactoriesSize() {
    return 1;
  }
  // 默认的转换器工厂列表为空列表
    List<? extends Converter.Factory> defaultConverterFactories() {
    return emptyList();
  }
  // 是否是默认方法
    boolean isDefaultMethod(Method method) {
    return false;
  }
  // 调用指定类默认的方法会抛异常,即不支持调用非默认方法
 @Nullable Object invokeDefaultMethod(Method method, Class<?> declaringClass, Object object,
      @Nullable Object... args) throws Throwable {
    throw new UnsupportedOperationException();
  }
    ...
    
}
  • isDefaultMethod()返回false,表示传入的Method都告知不是默认方法(默认方法是一种公共的非抽象实例方法,即带有主体的非静态方法,在接口中声明)
  • invokeDefaultMethod返回异常,表示调用非默认方法不支持

 

android

static class Android extends Platform {
    // 平台默认的回调执行器 回调线程是UI线程
    @Override public Executor defaultCallbackExecutor() {
      return new MainThreadExecutor();
    }
    // 是否是默认方法
    @Override boolean isDefaultMethod(Method method) {
    // 如果安卓构建版本小于24(安卓7.0),则直接返回是非默认方法,否则正常返回method.isDefault()
      if (Build.VERSION.SDK_INT < 24) {
        return false;
      }
      return method.isDefault();
    }
    //回调执行器必须不为空,回调适配器工厂列表版本小于Android7返回new DefaultCallAdapterFactory(callbackExecutor)单独组成的不可变list,否则返回CompletableFutureCallAdapterFactory.INSTANCE和DefaultCallAdapterFactory(callbackExecutor)组成的不可变list
    @Override List<? extends CallAdapter.Factory> defaultCallAdapterFactories(
        @Nullable Executor callbackExecutor) {
      if (callbackExecutor == null) throw new AssertionError();
      DefaultCallAdapterFactory executorFactory = new DefaultCallAdapterFactory(callbackExecutor);
      // CompletableFutureCallAdapterFactory是支持CompletableFutureCall,是java8特性
      return Build.VERSION.SDK_INT >= 24
        ? asList(CompletableFutureCallAdapterFactory.INSTANCE, executorFactory)
        : singletonList(executorFactory);
    }
    // 默认的回调适配器工程个数,和defaultCallAdapterFactories对应
    @Override int defaultCallAdapterFactoriesSize() {
      return Build.VERSION.SDK_INT >= 24 ? 2 : 1;
    }
    // 默认的转换器工厂
    @Override List<? extends Converter.Factory> defaultConverterFactories() {
    // 如果平台支持java8,则让Converter支持java8操作符
      return Build.VERSION.SDK_INT >= 24
          ? singletonList(OptionalConverterFactory.INSTANCE)
          : Collections.<Converter.Factory>emptyList();
    }
    // 默认转换器工厂个数
    @Override int defaultConverterFactoriesSize() {
      return Build.VERSION.SDK_INT >= 24 ? 1 : 0;
    }

    //安卓平台的主线程执行器
    static class MainThreadExecutor implements Executor {
      private final Handler handler = new Handler(Looper.getMainLooper());

      @Override public void execute(Runnable r) {
        handler.post(r);
      }
    }
  }
  • Android有默认的MainThreadExecutor,就是Android主线程任务执行器,默认的CallAdapter.Factory任务回调适配器工厂。
  • 从这里就可以看出Android平台上,Retrofit执行任务默认是在主线程。

 

Java8

static class Java8 extends Platform {
  // 默认method.isDefault()
    @Override boolean isDefaultMethod(Method method) {
      return method.isDefault();
    }
    // 支持调用默认方法
    @Override Object invokeDefaultMethod(Method method, Class<?> declaringClass, Object object,
        @Nullable Object... args) throws Throwable {
      // Because the service interface might not be public, we need to use a MethodHandle lookup
      // that ignores the visibility of the declaringClass.
       //Java反射机制的构造器
      Constructor<Lookup> constructor = Lookup.class.getDeclaredConstructor(Class.class, int.class);
      constructor.setAccessible(true);
      return constructor.newInstance(declaringClass, -1 /* trusted */)
          .unreflectSpecial(method, declaringClass)
          .bindTo(object)
          .invokeWithArguments(args);
    }
    // 默认适配器工厂列表,和Android差不多
    @Override List<? extends CallAdapter.Factory> defaultCallAdapterFactories(
        @Nullable Executor callbackExecutor) {
      List<CallAdapter.Factory> factories = new ArrayList<>(2);
      factories.add(CompletableFutureCallAdapterFactory.INSTANCE);
      factories.add(new DefaultCallAdapterFactory(callbackExecutor));
      return unmodifiableList(factories);
    }
    // 默认适配器工厂个数
     @Override int defaultCallAdapterFactoriesSize() {
      return 2;
    }
    // 默认转换器工厂列表
    @Override List<? extends Converter.Factory> defaultConverterFactories() {
      return singletonList(OptionalConverterFactory.INSTANCE);
    }
    // 默认转换器工厂个数
    @Override int defaultConverterFactoriesSize() {
      return 1;
    }
  }

 

Retrofit源码分析之二

Retrofit源码分析之三

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值