android

retrofit源码解析--基本使用和关键成员变量介绍

2019-03-18  本文已影响2人  二妹是只猫
Retrofit.png
retrofit将okhttp进行封装,使用注解将请求抽象成接口来使用。retrofit本身只是一个网络请求框架的封装

1.创建Retrofit并设置基本参数:

   Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("baseurl")
                //添加转化器
                .addConverterFactory(GsonConverterFactory.create())
                //添加rxjava支持
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .build();

2.创建请求接口:

   public interface retrofitService {
        @GET("try")
        public Call getCall();
    }

这里填写的try最终后baseurl拼接成完整的接口(baseurl+try)
3.通过创建出来的Retrofit获取网络请求接口:

 retrofitService retrofitService = retrofit.create(retrofitService.class);

4.通过接口获取请求方法:

Call call = retrofitService.getCall();

5.进行网络请求:

    call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {

            }
        });

完整代码:

   Retrofit retrofit = new Retrofit.Builder()
            .baseUrl("baseurl")
            .addConverterFactory(GsonConverterFactory.create())
            .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
            .build();
    retrofitService retrofitService = retrofit.create(retrofitService.class);
    Call call = retrofitService.getCall();
        call.enqueue(new Callback() {
        @Override
        public void onFailure(Call call, IOException e) {

        }

        @Override
        public void onResponse(Call call, Response response) throws IOException {

        }
    });
总结:
retrofit的网络通信的8步骤:
7个关键成员变量:
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> adapterFactories;
  final @Nullable Executor callbackExecutor;
  final boolean validateEagerly;
...
上一篇 下一篇

猜你喜欢

热点阅读