【源码分析】Retrofit分析

本文详细剖析了Retrofit的使用过程,从创建Retrofit.Builder开始,逐步讲解设置baseUrl、添加转换工厂和适配器,直到构建Retrofit对象。接着阐述了通过retrofit.create()创建接口请求对象,解析注解并创建CallAdapter和ResponseConverter。进一步探讨了同步和异步网络请求的执行流程,特别是在enqueue方法中如何确保回调在主线程中执行,确保UI更新的安全性。
摘要由CSDN通过智能技术生成

1 Retrofit 使用

  mRetrofit = 
  new Retrofit.Builder() //1.1 
  .baseUrl(HttpConfig.baseURL)//1.2 配置服务器路径
  .addConverterFactory(MyGsonConverterFactory.create())//配置转化库,Gson//1.3 添加数据转换工厂
  .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) //1.4 添加网络请求适配器工厂 配置支持rxjava2
  .client(genericClient())
  .build(); //1.5 调用build方法创建Retrofit对象

1.1 创建 Retrofit.Builder(),Platform.get()根据不同平台返回不同的Platform

/**
	Platform.get()根据不同平台返回不同的Platform
**/

  public Builder() {
      this(Platform.get());
    }


  private static final Platform PLATFORM = findPlatform();

  static Platform get() {
    return PLATFORM;
  }

  private static Platform findPlatform() {
    try {
      Class.forName("android.os.Build");
      if (Build.VERSION.SDK_INT != 0) {
        return new Android();
      }
    } catch (ClassNotFoundException ignored) {
    }
    try {
      Class.forName("java.util.Optional");
      return new Java8();
    } catch (ClassNotFoundException ignored) {
    }
    return new Platform();
  }
/**
	android平台的Platform对象
**/
static class Android extends Platform {
    @IgnoreJRERequirement // Guarded by API check.
    @Override boolean isDefaultMethod(Method method) {
      if (Build.VERSION.SDK_INT < 24) {
        return false;
      }
      return method.isDefault();
    }

    @Override public Executor defaultCallbackExecutor() { //初始化主线程的执行器
      return new MainThreadExecutor();
    }

    @Override List<? extends CallAdapter.Factory> defaultCallAdapterFactories(
        @Nullable Executor callbackExecutor) {
      if (callbackExecutor == null) throw new AssertionError();
      DefaultCallAdapterFactory executorFactory = new DefaultCallAdapterFactory(callbackExecutor);
      return Build.VERSION.SDK_INT >= 24
        ? asList(CompletableFutureCallAdapterFactory.INSTANCE, executorFactory)
        : singletonList(executorFactory);
    }

    @Override int defaultCallAdapterFactoriesSize() {
      return Build.VERSION.SDK_INT >= 24 ? 2 : 1;
    }

    @Override List<? extends Converter.Factory> defaultConverterFactories() { //初始化默认数据转换器
      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);
      }
    }
  }

1.2 设置baseUrl , 将URL设置到retrofit

public Builder baseUrl(String baseUrl) {
  checkNotNull(baseUrl, "baseUrl == null");
  return baseUrl(HttpUrl.get(baseUrl));
}

public Builder baseUrl(HttpUrl baseUrl) {
  checkNotNull(baseUrl, "baseUrl == null");
  List<String> pathSegments = baseUrl.pathSegments();
  if (!"".equals(pathSegments.get(pathSegments.size() - 1))) {
    throw new IllegalArgumentException("baseUrl must end in /: " + baseUrl);
  }
  this.baseUrl = baseUrl;
  return this;
}

1.3 添加数据转换工厂

/**
	 将设置的数据转换添加进来,converterFactories为一个list方法
**/
  public Builder addConverterFactory(Converter.Factory factory) {
      converterFactories.add(checkNotNull(factory, "factory == null"));
      return this;
    }

1.4 添加网络请求适配器工厂

/**
	 将网络请求适配器工厂添加进来
**/
public Builder addCallAdapterFactory(CallAdapter.Factory factory) {
  callAdapterFactories.add(checkNotNull(factory, "factory == null"));
  return this;
}

1.5 调用build方法创建Retrofit对象

 public Retrofit build() {
      if (baseUrl == null) { //判断basrUrl为空
        throw new IllegalStateException("Base URL required.");
      }

      okhttp3.Call.Factory callFactory = this.callFactory; //获取网络请求工厂,如果为空则创建为OKHttp
      if (callFactory == null) {
        callFactory = new OkHttpClient();
      }

      Executor callbackExecutor = this.callbackExecutor; //获取回调执行器,为空则调用platform默认执行器
      if (callbackExecutor == null) {
        callbackExecutor = platform.defaultCallbackExecutor();
      }

      // Make a defensive copy of the adapters and add the default Call adapter.
      //创建网络请求工厂集合,并加入默认的网络适配器工厂
      List<CallAdapter.Factory> callAdapterFactories = new ArrayList<>(this.callAdapterFactories);
      callAdapterFactories.addAll(platform.defaultCallAdapterFactories(callbackExecutor));

      // Make a defensive copy of the converters.
      //创建数据转换工厂集合
      List<Converter.Factory> converterFactories = new ArrayList<>(
          1 + this.converterFactories.size() + platform.defaultConverterFactoriesSize());

      // Add the built-in converter factory first. This prevents overriding its behavior but also
      // ensures correct behavior when using converters that consume all types.
      //添加内置的数据转换工厂
      converterFactories.add(new BuiltInConverters());
      //添加外部添加的数据转换工厂
      converterFactories.addAll(this.converterFactories);
      //添加platform默认的数据转换工厂
      converterFactories.addAll(platform.defaultConverterFactories());
	  //返回创建的retrofit对象
      return new Retrofit(callFactory, baseUrl, unmodifiableList(converterFactories),
          unmodifiableList(callAdapterFactories), callbackExecutor, validateEagerly);
    }
/**
	 Retrofit 对象
**/
public final class Retrofit {
  private final Map<Method, ServiceMethod<?>> serviceMethodCache = new ConcurrentHashMap<>();

  final okhttp3.Call.Factory callFactory;
  final HttpUrl baseUrl;
  //数据转换器工厂集合
  final List<Converter.Factory> converterFactories;
  //网络请求适配器工厂集合
  final List<CallAdapter.Factory> callAdapterFactories;、
  //回调执行器
  final @Nulla
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值