美文网首页Android知识
Retrofit2.0 源码解析

Retrofit2.0 源码解析

作者: _SHYII | 来源:发表于2017-04-07 18:04 被阅读0次

    首先介绍下Retrofit基本用法,先创建接口,注解申明、请求方式Post/Get等

    public interface Service {
    
        @POST("list")
        Call<User> loadRepo();
    
    }
    
    

    基本使用如下

    Retrofit retrofit = new Retrofit.Builder()
                    .baseUrl("http://www.jianshu.com/u/c030e2bc8731")
                    .build();
    
            Service service = retrofit.create(Service.class);
            Call<User> userCall = service.loadRepo();
    
            userCall.enqueue(new Callback<User>() {
                @Override
                public void onResponse(Call<User> call, Response<User> response) {
    
                }
    
                @Override
                public void onFailure(Call<User> call, Throwable t) {
    
                }
            });
    

    上面是简单的网络请求流程,那么我们来分析具体是怎么实现的,直接看源码

    Retrofit.Builder()方法

    首先Retrofit.Builder()中Platform.get()最后调用findPlatform()得到平台信息,可以看到支持Android、Java8平台,其中还对Converter.Factory 设置默认值。

      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();
      }
    
    Retrofit.Builder().builder()方法
        public Retrofit build() {
          //baseUrl必须不为空
          if (baseUrl == null) {
            throw new IllegalStateException("Base URL required.");
          }
          //OkHttpClient对象
          okhttp3.Call.Factory callFactory = this.callFactory;
          if (callFactory == null) {
            callFactory = new OkHttpClient();
          }
          //将回调传递,此时platform为Android 平台,在Retrofit.Builder()中初始化
          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> adapterFactories = new ArrayList<>(this.adapterFactories);
          //将callbackExecutor转化成ExecutorCallAdapterFactory并添加到adapterFactories 集合中
          adapterFactories.add(platform.defaultCallAdapterFactory(callbackExecutor));
    
          // Make a defensive copy of the converters.
          List<Converter.Factory> converterFactories = new ArrayList<>(this.converterFactories);
    
          return new Retrofit(callFactory, baseUrl, converterFactories, adapterFactories,
              callbackExecutor, validateEagerly);
        }
    

    1)以上可见baseUrl必须传,null则抛出异常。
    2)若未传入OkHttpClient则默认创建一个,此处callFactory即OkHttpClient对象,OkHttpClient实现了okhttp3.Call.Factory接口。
    3)callbackExecutor,是用来将回调切换到主线程中去,此处利用platform对象,对平台进行判断,判断主要是利用Class.forName("")进行查找,如果是Android平台,会自定义一个Executor对象MainThreadExecutor,并且利用Looper.getMainLooper()实例化一个handler对象,在Executor内部通过handler.post(runnable),代码如下:

      static class Android extends Platform {
        @Override public Executor defaultCallbackExecutor() {
          return new MainThreadExecutor();
        }
    
        @Override CallAdapter.Factory defaultCallAdapterFactory(Executor callbackExecutor) {
          return new ExecutorCallAdapterFactory(callbackExecutor);
        }
    
        static class MainThreadExecutor implements Executor {
          private final Handler handler = new Handler(Looper.getMainLooper());
    
          @Override public void execute(Runnable r) {
            handler.post(r);
          }
        }
      }
    

    4)adapterFactories,这个对象主要用于对Call进行转化。创建callbackExecutor即MainThreadExecutor对象,MainThreadExecutor
    5)converterFactories 转换器工厂,该对象用于转化数据,例如将返回的responseBody转化为对象等;当然不仅仅是针对返回的数据,还能用于一般备注解的参数的转化例如@Body标识的对象做一些操作等。

    retrofit.create(Service.class)
      public <T> T create(final Class<T> service) {
        Utils.validateServiceInterface(service);
        ......
        return (T) Proxy.newProxyInstance(service.getClassLoader(), new Class<?>[] { service },
            new InvocationHandler() {
                ......
              @Override public Object invoke(Object proxy, Method method, Object[] args)
                  throws Throwable {
                ......
                ServiceMethod<Object, Object> serviceMethod = (ServiceMethod<Object, Object>) loadServiceMethod(method);
                OkHttpCall<Object> okHttpCall = new OkHttpCall<>(serviceMethod, args);
                return serviceMethod.callAdapter.adapt(okHttpCall);
              }
            });
      }
    

    分三个步骤,第一根据我们的method将其包装成ServiceMethod,第二通过ServiceMethod和方法的参数构造retrofit2.OkHttpCall对象,第三通过serviceMethod.callAdapter.adapt()方法,将OkHttpCall进行代理包装;

    1>将method包装成ServiceMethod

    下面看Retrofit的loadServiceMethod()方法:

      ServiceMethod<?, ?> loadServiceMethod(Method method) {
        ServiceMethod<?, ?> result = serviceMethodCache.get(method);
        if (result != null) return result;
    
        synchronized (serviceMethodCache) {
          result = serviceMethodCache.get(method);
          if (result == null) {
            result = new ServiceMethod.Builder<>(this, method).build();
            serviceMethodCache.put(method, result);
          }
        }
        return result;
      }
    

    可见将method缓存在Map中,所以Retrofit带有缓存,第二次网络请求相同方法时,会避免创建实例化和解析注解,减少响应时间。

    ServiceMethod.build():

        public ServiceMethod build() {
          callAdapter = createCallAdapter();
          responseType = callAdapter.responseType();
          if (responseType == Response.class || responseType == okhttp3.Response.class) {
            throw methodError("'"
                + Utils.getRawType(responseType).getName()
                + "' is not a valid response body type. Did you mean ResponseBody?");
          }
          responseConverter = createResponseConverter();
    
          for (Annotation annotation : methodAnnotations) {
            parseMethodAnnotation(annotation);
          }
    
          if (httpMethod == null) {
            throw methodError("HTTP method annotation is required (e.g., @GET, @POST, etc.).");
          }
    
          if (!hasBody) {
            if (isMultipart) {
              throw methodError(
                  "Multipart can only be specified on HTTP methods with request body (e.g., @POST).");
            }
            if (isFormEncoded) {
              throw methodError("FormUrlEncoded can only be specified on HTTP methods with "
                  + "request body (e.g., @POST).");
            }
          }
    
          int parameterCount = parameterAnnotationsArray.length;
          parameterHandlers = new ParameterHandler<?>[parameterCount];
          for (int p = 0; p < parameterCount; p++) {
            Type parameterType = parameterTypes[p];
            if (Utils.hasUnresolvableType(parameterType)) {
              throw parameterError(p, "Parameter type must not include a type variable or wildcard: %s",
                  parameterType);
            }
    
            Annotation[] parameterAnnotations = parameterAnnotationsArray[p];
            if (parameterAnnotations == null) {
              throw parameterError(p, "No Retrofit annotation found.");
            }
    
            parameterHandlers[p] = parseParameter(p, parameterType, parameterAnnotations);
          }
    
          if (relativeUrl == null && !gotUrl) {
            throw methodError("Missing either @%s URL or @Url parameter.", httpMethod);
          }
          if (!isFormEncoded && !isMultipart && !hasBody && gotBody) {
            throw methodError("Non-body HTTP method cannot contain @Body.");
          }
          if (isFormEncoded && !gotField) {
            throw methodError("Form-encoded method must contain at least one @Field.");
          }
          if (isMultipart && !gotPart) {
            throw methodError("Multipart method must contain at least one @Part.");
          }
    
          return new ServiceMethod<>(this);
        }
    

    1)以上代码中callAdapter为在Retrofit.Builder.build中platform.defaultCallAdapterFactory(callbackExecutor)创建,在createCallAdapter()中获取方法的注解和Bean的数据类型,最后调用ExecutorCallAdapterFactory.get()取出,callAdapter的作用是将回调传递到UI线程。
    2)callAdapter.responseType()返回的是我们方法的实际类型,例如:Call<User>,则返回User类型,然后对该类型进行判断。
    3)createResponseConverter()得到responseConverter转换器对象,它的作用是寻找合适的数据类型转换器。在构建retrofit时,addConverterFactory添加的ConverterFactory对象来寻找一个合适的返回,寻找的依据主要看该converter能否处理你编写方法的返回值类型,默认实现为BuiltInConverters,仅仅支持返回值的实际类型为ResponseBody和Void,也就说明了默认情况下,是不支持Call<User>这类类型的。

    2>通过ServiceMethod和方法的参数构造retrofit2.OkHttpCall对象

    OkHttpCall构造方法中对方法参数进行赋值

      OkHttpCall(ServiceMethod<T, ?> serviceMethod, Object[] args) {
        this.serviceMethod = serviceMethod;
        this.args = args;
      }
    
    3>通过serviceMethod.callAdapter.adapt()方法,将OkHttpCall进行代理包装
    serviceMethod.callAdapter.adapt(okHttpCall)

    上面说了callAdapter通过CallAdapter<?, ?> adapter = adapterFactories.get(i).get(returnType, annotations, this);获得,而adapterFactories.get(i)得到的call对象是ExecutorCallAdapterFactory。当通过retrofit的create()方法再获得call对象,调用call.enque()去访问网络时,方法中有回掉函数,回掉函数里重写两个方法,一个成功,一个失败;这个call对象其实就是ExcutorCallAdapterFactory。callAdapter是ExecutorCallAdapterFactory.get()方法得到的。

    看return new CallAdapter中的adapt(Call call)我们可以知道,在我们得到接口的代理实例之后,通过代理接口调用里面的方法,就会触发InvocationHandler对象中的invoke方法,从而完成上面的三个步骤并且返回一个Call对象,通过Call对象就可以去完成我们的请求了。

    从下面代码可以看出adapt返回的是ExecutorCallbackCall对象。

    final class ExecutorCallAdapterFactory extends CallAdapter.Factory {
      final Executor callbackExecutor;
    
      ExecutorCallAdapterFactory(Executor callbackExecutor) {
        this.callbackExecutor = callbackExecutor;
      }
    
      @Override
      public CallAdapter<?, ?> get(Type returnType, Annotation[] annotations, Retrofit retrofit) {
        if (getRawType(returnType) != Call.class) {
          return null;
        }
        final Type responseType = Utils.getCallResponseType(returnType);
        // return new CallAdapter
        return new CallAdapter<Object, Call<?>>() {
          @Override public Type responseType() {
            return responseType;
          }
    
          @Override public Call<Object> adapt(Call<Object> call) {
            return new ExecutorCallbackCall<>(callbackExecutor, call);
          }
        };
      }
    

    再看下面代码可以看出ExecutorCallbackCall是对 Call<T> delegate 的封装,delegate 就是OkHttpCall对象,enqueue即是调用OkHttpCall的方法enqueue而已。

      static final class ExecutorCallbackCall<T> implements Call<T> {
        final Executor callbackExecutor;
        final Call<T> delegate;
    
        ExecutorCallbackCall(Executor callbackExecutor, Call<T> delegate) {
          this.callbackExecutor = callbackExecutor;
          this.delegate = delegate;
        }
    
        @Override public void enqueue(final Callback<T> callback) {
          if (callback == null) throw new NullPointerException("callback == null");
    
          delegate.enqueue(new Callback<T>() {
            @Override public void onResponse(Call<T> call, final Response<T> response) {
              callbackExecutor.execute(new Runnable() {
                @Override public void run() {
                  if (delegate.isCanceled()) {
                    // Emulate OkHttp's behavior of throwing/delivering an IOException on cancellation.
                    callback.onFailure(ExecutorCallbackCall.this, new IOException("Canceled"));
                  } else {
                    callback.onResponse(ExecutorCallbackCall.this, response);
                  }
                }
              });
            }
    
            @Override public void onFailure(Call<T> call, final Throwable t) {
              callbackExecutor.execute(new Runnable() {
                @Override public void run() {
                  callback.onFailure(ExecutorCallbackCall.this, t);
                }
              });
            }
          });
        }
    

    再来看OkHttpCall的方法enqueue()方法,也是调用okhttp3.Call的enqueue()方法,下面代码中可以看到 createRawCall()中对okhttp3.Call初始化;另通过parseResponse()构建Response对象。

      @Override public void enqueue(final Callback<T> callback) {
        if (callback == null) throw new NullPointerException("callback == null");
    
        okhttp3.Call call;
        Throwable failure;
    
        synchronized (this) {
          if (executed) throw new IllegalStateException("Already executed.");
          executed = true;
    
          call = rawCall;
          failure = creationFailure;
          if (call == null && failure == null) {
            try {
              //okhttp3.Call call初始化
              call = rawCall = createRawCall();
            } catch (Throwable t) {
              failure = creationFailure = t;
            }
          }
        }
    
        if (failure != null) {
          callback.onFailure(this, failure);
          return;
        }
    
        if (canceled) {
          call.cancel();
        }
    
        call.enqueue(new okhttp3.Callback() {
          @Override public void onResponse(okhttp3.Call call, okhttp3.Response rawResponse)
              throws IOException {
            Response<T> response;
            try {
              //构造Response对象
              response = parseResponse(rawResponse);
            } catch (Throwable e) {
              callFailure(e);
              return;
            }
            callSuccess(response);
          }
    
          @Override public void onFailure(okhttp3.Call call, IOException e) {
            try {
              callback.onFailure(OkHttpCall.this, e);
            } catch (Throwable t) {
              t.printStackTrace();
            }
          }
    
          private void callFailure(Throwable e) {
            try {
              callback.onFailure(OkHttpCall.this, e);
            } catch (Throwable t) {
              t.printStackTrace();
            }
          }
    
          private void callSuccess(Response<T> response) {
            try {
              callback.onResponse(OkHttpCall.this, response);
            } catch (Throwable t) {
              t.printStackTrace();
            }
          }
        });
      }
    

    createRawCall() 中通过serviceMethod.toRequest()构造Requset对象,再通过request构造call对象。

      private okhttp3.Call createRawCall() throws IOException {
        Request request = serviceMethod.toRequest(args);
        okhttp3.Call call = serviceMethod.callFactory.newCall(request);
        if (call == null) {
          throw new NullPointerException("Call.Factory returned null.");
        }
        return call;
      }
    

    parseResponse()是中逻辑为通过serviceMethod对ResponseBody进行转化,然后返回,转化实际上就是通过responseConverter的convert方法。

      Response<T> parseResponse(okhttp3.Response rawResponse) throws IOException {
        ResponseBody rawBody = rawResponse.body();
         ......
        ExceptionCatchingRequestBody catchingBody = new ExceptionCatchingRequestBody(rawBody);
        T body = serviceMethod.toResponse(catchingBody);
        return Response.success(body, rawResponse);
      }
    
      R toResponse(ResponseBody body) throws IOException {
        return responseConverter.convert(body);
      }
    

    好了关于Retrofit2.0的源码分析就到这里,下面总结一下:
    1)首先构造retrofit,核心的参数是baseurl,callFactory(默认okhttpclient)、converterFactories、adapterFactories、excallbackExecutor。
    2)其次通过create得到接口的实现类,利用Proxy类完成动态代理的相关代理。在我们得到接口的代理实例之后,通过代理接口调用里面的方法,就会触发InvocationHandler对象中的invoke方法,从而完成上面的三个步骤并且返回一个Call对象。
    3)拿到Call执行enqueue或者execute方法。
    由此Retrofit完成整个请求回调流程。


    参考:
    Retrofit2 完全解析 探索与okhttp之间的关系
    Retrofi2源码解析(二)

    相关文章

      网友评论

        本文标题:Retrofit2.0 源码解析

        本文链接:https://www.haomeiwen.com/subject/ljbqattx.html