Retrofit - 10 中build方法完成retrofit对象创建流程解析

本文介绍如何使用配置好的参数创建Retrofit实例。文中详细说明了在构造过程中对BaseUrl、网络请求执行器、回调方法执行器等组件的处理流程,并介绍了如何初始化适配器工厂和转换器工厂。

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

/**
     * Create the {@link Retrofit} instance using the configured values.
     * <p>
     * Note: If neither {@link #client} nor {@link #callFactory} is called a default {@link
     * OkHttpClient} will be created and used.
     */
    public Retrofit build() {
      // 对baseUrl进行判空
      if (baseUrl == null) {
        throw new IllegalStateException("Base URL required.");
      }
      // 网络请求执行器
      okhttp3.Call.Factory callFactory = this.callFactory;
      if (callFactory == null) {
        callFactory = new OkHttpClient();
      }
      // 初始化回掉方法执行器,主要用在异步请求
      Executor callbackExecutor = this.callbackExecutor;
      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.add(platform.defaultCallAdapterFactory(
               callbackExecutor));
      // Make a defensive copy of the converters.
      List<Converter.Factory> converterFactories =
          new ArrayList<>(1 + this.converterFactories.size());
// 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);

return new Retrofit(callFactory, baseUrl, 
          unmodifiableList(converterFactories),
          unmodifiableList(callAdapterFactories), callbackExecutor, 
                 validateEagerly);
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值