Retrofit的创建

379 阅读1分钟

流程图

image.png

Retrofit使用

Retrofit retrofit = new Retrofit.Builder()
        .baseUrl("http://xxx.xxx.com/") // 设置网络请求的Url地址
        .addConverterFactory(GsonConverterFactory.create()) // 设置数据解析器
        .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) // 支持RxJava平台
        .build();

MyInterface myInterface = retrofit.create(MyInterface.class);

Call call = myInterface.getCall();
//retrofit同步请求
call.execute();

call.enqueue(new retrofit2.Callback() {
    @Override
    public void onResponse(Call call, retrofit2.Response response) {
        System.out.println(response.body());
    }

    @Override
    public void onFailure(Call call, Throwable throwable) {
        System.out.println("请求失败");
    }
});

public interface MyInterface {

    @GET(".../...")
    Call<List<MyResponse>> getCall();
}

创建 Retrofit 源码解析

首先看下Builder参数。

public static final class Builder {
 
    // 平台类型对象(Platform -> Android)
    private final Platform platform;
    // 网络请求工厂,默认使用OkHttpCall(工厂方法模式)
    private Factory callFactory;
    // 网络请求的url地址
    private @Nullable HttpUrl baseUrl;
    // 数据转换器工厂,将网络获取的Response转换成我们可以使用的Java对象。
    private final List<Converter.Factory> converterFactories = new ArrayList<>();
    // 网络请求适配器工厂的集合,默认是ExecutorCallAdapterFactory
    private final List<CallAdapter.Factory> callAdapterFactories = new ArrayList<>();
    // 回调方法执行器,在 Android 上默认是封装了 handler 的 MainThreadExecutor, 默认作用是:切换线程(子线程 -> 主线程)
    private @Nullable Executor callbackExecutor;
    // 一个开关,为true则会缓存创建的ServiceMethod
    private boolean validateEagerly;
    
    
    public Retrofit build() {
    if (baseUrl == null) {
    throw new IllegalStateException("Base URL required.");
    }

    okhttp3.Call.Factory callFactory = this.callFactory;
    if (callFactory == null) {
    (1)默认使用Okhttp做网络请求
    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.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.2)添加默认的数据转换器工厂
    converterFactories.add(new BuiltInConverters());
    converterFactories.addAll(this.converterFactories);
    converterFactories.addAll(platform.defaultConverterFactories());

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

Platform

看下是怎么获取平台信息的。

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

很简单,通过反射的方式获取。

class Platform {
    private static final Platform PLATFORM = findPlatform();

    Platform() {
    }

    static Platform get() {
        return PLATFORM;
    }

    private static Platform findPlatform() {
        try {
            (1)通过反射的方式。
            Class.forName("android.os.Build");
            if (VERSION.SDK_INT != 0) {
                return new Platform.Android();
            }
        } catch (ClassNotFoundException var3) {
        }

        try {
            Class.forName("java.util.Optional");
            return new Platform.Java8();
        } catch (ClassNotFoundException var2) {
            try {
                Class.forName("org.robovm.apple.foundation.NSObject");
                return new Platform.IOS();
            } catch (ClassNotFoundException var1) {
                return new Platform();
            }
        }
    }
 }

converterFactories

看下默认实现

很简单,就是new了一个Gson对象。

public final class GsonConverterFactory extends Factory {
    private final Gson gson;

    public static GsonConverterFactory create() {
        return create(new Gson());
    }

    public static GsonConverterFactory create(Gson gson) {
        return new GsonConverterFactory(gson);
    }

    private GsonConverterFactory(Gson gson) {
        if (gson == null) {
            throw new NullPointerException("gson == null");
        } else {
            this.gson = gson;
        }
    }

    public Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations, Retrofit retrofit) {
        TypeAdapter<?> adapter = this.gson.getAdapter(TypeToken.get(type));
        return new GsonResponseBodyConverter(this.gson, adapter);
    }

    public Converter<?, RequestBody> requestBodyConverter(Type type, Annotation[] parameterAnnotations, Annotation[] methodAnnotations, Retrofit retrofit) {
        TypeAdapter<?> adapter = this.gson.getAdapter(TypeToken.get(type));
        return new GsonRequestBodyConverter(this.gson, adapter);
    }
}

callbackExecutor

用于切换线程的,将异步线程切换回主线程。Glide也是通过Handler。

默认实现

static class MainThreadExecutor implements Executor {
  private final Handler handler = new Handler(Looper.getMainLooper());

  @Override public void execute(Runnable r) {
    handler.post(r);
  }
}

总结:

  1. 通过反射对平台赋值。
  2. 初始化网络请求工厂,默认是OkHttpClient。
  3. 初始化数据适配器工厂。
  4. 初始化网络适配器工厂。
  5. 初始化了网络回包数据切换线程的Executor。

参考:

  1. Retrofit分析-漂亮的解耦套路

  2. 慕课网