Retrofit 源码解析

Retrofit 源码解析

1 retrofit 的创建

1.1 官方Demo

Retrofit retrofit = new Retrofit.Builder()
    .baseUrl("https://api.github.com/")
    .build();

1.2 Retrofit 类的解析

public final class Retrofit {
    ....
  private final List<Converter.Factory> converterFactories;
  private final List<CallAdapter.Factory> adapterFactories;

    .....

    public static final class Builder {
        public Builder baseUrl(String baseUrl) {...}
        public Builder addCallAdapterFactory(CallAdapter.Factory factory) {...}
        ......
         public Retrofit build() {
            ........
            retrurn new Retrofit(...);
         }
    }

}
  • 内部类Builder 是Retrofit 的构造器可以调入Builder的各种方法为Retrofit添加各种组件 如:
    1. addConverterFactory(GsonConverterFactory.create()) 添加Gson转换器可将json装换成相应的类
    2. addCallAdapterFactory(CallAdapter.Factory factory)
      …..
      最后调用build()会返回Retrofit的实例

2 动态代理生成代理类

2.1 官方Demo

接口

public interface GitHubService {
  @GET("users/{user}/repos")
  Call<List<Repo>> listRepos(@Path("user") String user);
}

根据接口生成代理类

Retrofit retrofit = new Retrofit.Builder()
    .baseUrl("https://api.github.com/")
    .build();

GitHubService service = retrofit.create(GitHubService.class);

2.2 源码解析

2.2.1 create()方法

create()方法是Rtrofit类中的一个重要的方法,通过调用该方法Retrofit可以利用动态代理的方式来生成传入接口的地代理类,create()的方法如下:

 @SuppressWarnings("unchecked") // Single-interface proxy creation guarded by parameter safety.
  public <T> T create(final Class<T> service) {
    Utils.validateServiceInterface(service);
    if (validateEagerly) {
      eagerlyValidateMethods(service);
    }
    return (T) Proxy.newProxyInstance(service.getClassLoader(), new Class<?>[] { service },
        new InvocationHandler() {
          private final Platform platform = Platform.get();

          @Override public Object invoke(Object proxy, Method method, Object... args)
              throws Throwable {
            // If the method is a method from Object then defer to normal invocation.
            if (method.getDeclaringClass() == Object.class) {
              return method.invoke(this, args);
            }
            if (platform.isDefaultMethod(method)) {
              return platform.invokeDefaultMethod(method, service, proxy, args);
            }
            ServiceMethod<Object, Object> serviceMethod =
                (ServiceMethod<Object, Object>) loadServiceMethod(method);
            OkHttpCall<Object> okHttpCall = new OkHttpCall<>(serviceMethod, args);
            return serviceMethod.callAdapter.adapt(okHttpCall);
          }
        });
  }
  • 第三行的代码判断了传入的service是否是一个接口
  • 在第七行,return返回了该接口的一个代理类,同时在第14行和17行的代码中,代理类过滤了非接口类自定义的方法
  • loadServiceMethod() 方法见该方法进行了解析,并将结果进行了缓存
  • new OkHttpCall<>(serviceMethod, args); 内部通过OkHttp的Call对象来进行网络访问
  • serviceMethod.callAdapter.adapt(okHttpCall);

2.2.2 loadServiceMethod(Method method)

loadServiceMethod()方法对拦截的方法进行了解析,拦截的方法以参数methoad方式传入,同时为了提高效率在对方法进行解析式,先在在缓存中进行查找,如果找到在进行戒解析,同时对结果进行缓存。最后以ServiceMethoad的形式返回给调用者。

  ServiceMethod<?, ?> loadServiceMethod(Method method) {
  //  Map<Method, ServiceMethod<?, ?>> serviceMethodCache 
    ServiceMethod<?, ?> result = serviceMethodCache.get(method);
    //缓存查找失败
    if (result != null) return result;

    synchronized (serviceMethodCache) {
      result = serviceMethodCache.get(method);
      if (result == null) {
      //构建ServiceMethod
        result = new ServiceMethod.Builder<>(this, method).build();
        serviceMethodCache.put(method, result);
      }
    }
    return result;
  }

2.2.3 ServiceMethod 解析

在loadServiceMethod中最重要的一部是构建ServicerMethod对象,在创建该对象的过程中完成了对方法注解的解析以及CallAdapter和ResponseConverter的创建

final class ServiceMethod<R, T> {
     ......
         static final class Builder<T, R> {
            ......
           public Builder(Retrofit retrofit, Method method) {
                this.retrofit = retrofit;
               this.method = method;
              this.methodAnnotations = method.getAnnotations();
              this.parameterTypes = method.getGenericParameterTypes();
               this.parameterAnnotationsArray = method.getParameterAnnotations();
                }

             public ServiceMethod build() {
                 . ....
                   callAdapter = createCallAdapter();
                   responseConverter = createResponseConverter();
                   ......
                  for (Annotation annotation : methodAnnotations) {
                    parseMethodAnnotation(annotation);
                  }
                   .....
                   Annotation[] parameterAnnotations = parameterAnnotationsArray[p];
                    ....
                   return new ServiceMethod<>(this);

             }

         }
}
  • 创建CallAdapter
    CallAdapter的创建首先待用了ServiceMethoad中的createCallAdapter()方法
 private CallAdapter<T, R> createCallAdapter() {
      Type returnType = method.getGenericReturnType();
      if (Utils.hasUnresolvableType(returnType)) {
        throw methodError(
            "Method return type must not include a type variable or wildcard: %s", returnType);
      }
      if (returnType == void.class) {
        throw methodError("Service methods cannot return void.");
      }
      Annotation[] annotations = method.getAnnotations();
      try {
        //noinspection unchecked
        return (CallAdapter<T, R>) retrofit.callAdapter(returnType, annotations);
      } catch (RuntimeException e) { // Wide exception range because factories are user code.
        throw methodError(e, "Unable to create call adapter for %s", returnType);
      }
    }

而在该方法的最后实际是调用了Retrofit的callAdapter()方法,并将方法的注解和返回值作为了callAdapter的参数
- 调用Retrofit.callAdapter()
有callAdapter的源码可知,callAdapter实际是调用了nextCallAdapter

  public CallAdapter<?, ?> callAdapter(Type returnType, Annotation[] annotations) {
    return nextCallAdapter(null, returnType, annotations);
  }

在nextCallAdapter()方法中才返回了具体的CallAdapter的具体实例

 public CallAdapter<?, ?> nextCallAdapter(CallAdapter.Factory skipPast, Type returnType,
      Annotation[] annotations) {
       ......
           int start = adapterFactories.indexOf(skipPast) + 1;
           // adapterFactories 是一个List<CallAdapter.Factory>
          for (int i = start, count = adapterFactories.size(); i < count; i++) {
              CallAdapter<?, ?> adapter = adapterFactories.get(i).get(returnType, annotations, this);
              if (adapter != null) {
                return adapter;
              }
              ........
    }
 }

首先解释一下方法参数中的skipPash ,该参数的类型是CallAdapter.Factory,而CallAdapter是一个接口

public interface CallAdapter<R, T>{
    Type responseType(); 
  T adapt(Call<R> call);
  abstract class Factory {
    //在子类中实现,根据returnType的不同类型来返回实例,或者返回NULL
    public abstract CallAdapter<?, ?> get(Type returnType, Annotation[] annotations,
        Retrofit retrofit);
    protected static Type getParameterUpperBound(int index, ParameterizedType type) {
      return Utils.getParameterUpperBound(index, type);
    }
    protected static Class<?> getRawType(Type type) {
      return Utils.getRawType(type);
}

通过分析源码我们可以了解到CallAdapter.Factory是该接口中的一个抽象类,而继承了该抽象类的实现类有
GuavaCallAdapterFactory,Java8CallAdapterFactory,RxJavaCallAdapterFactory而这些类就是来创建具体的Adapter的,比如RxJavaCallAdapterFactory就是用来创建RxJavaCallAdapter。通过调用get()方法来返回具体的CallAdapter对象。我们可以自己来继承CallAdapter.Factory这个抽象类来实现自定义的CallAdapter,通过addCallAdapterFactory()方法来注入

返回到nextCallAdapter的代码中,在该方法中实际上是通过一个循环来遍历adapterFactories链表对其中的Factroy的get()方法进行调用,当遇到第一个不为空的get()方法的返回值时就结束循环返回结果,我们以RxJavaCallAdapterFactory为例来看看get()方法的具体实现

public final class RxJavaCallAdapterFactory extends CallAdapter.Factory {
    .....
    public CallAdapter<?, ?> get(Type returnType, Annotation[] annotations, Retrofit retrofit) {
         Class<?> rawType = getRawType(returnType);
        boolean isSingle = rawType == Single.class;
        boolean isCompletable = "rx.Completable".equals(rawType.getCanonicalName());
        //不符合创建条件返回NULL 
         if (rawType != Observable.class && !isSingle && !isCompletable) {
             return null;
          }
           if (isCompletable) {
              return new RxJavaCallAdapter(Void.class, scheduler, false, true, false, true);
           }
          //TODO
           '.........

    }
}

下面我们一RxJavaCallAdapter为例来分析一下CallAdapter的代码,各种类型的CallAdapter都是实现了CallAdapter接口,在每个CallAdapter类中有一个重要的Adapter方法

final class RxJavaCallAdapter<R> implements CallAdapter<R, Object>{

    RxJavaCallAdapter(Type responseType, Scheduler scheduler, boolean isResult, boolean isBody, boolean isSingle, boolean isCompletable) {
       //对方法中的各个参数进行了保存
    }

    //比较重要的一个方法,会在后面进行解析
    @Override public Object adapt(Call<R> call) {}
}
  • responseConverter = createResponseConverter();
    该语句创建了responseConverter,而responseConverter的创建过程与CallAdapter的创建过程相类似,同样是调用了createResponseConverter()
    private Converter<ResponseBody, T> createResponseConverter() {
      Annotation[] annotations = method.getAnnotations();
      try {
        return retrofit.responseBodyConverter(responseType, annotations);
      } catch (RuntimeException e) { // Wide exception range because factories are user code.
        throw methodError(e, "Unable to create converter for %s", responseType);
      }
    }

同样在Retrofit的responseBodyConverter也采用了与CallAdapter相同的创建方式,在Retrofit中

  public <T> Converter<ResponseBody, T> responseBodyConverter(Type type, Annotation[] annotations) {
    return nextResponseBodyConverter(null, type, annotations);
  }

public <T> Converter<ResponseBody, T> nextResponseBodyConverter(Converter.Factory skipPast,
      Type type, Annotation[] annotations) {
    checkNotNull(type, "type == null");
    checkNotNull(annotations, "annotations == null");

    int start = converterFactories.indexOf(skipPast) + 1;
    for (int i = start, count = converterFactories.size(); i < count; i++) {
      Converter<ResponseBody, ?> converter =
          converterFactories.get(i).responseBodyConverter(type, annotations, this);
      if (converter != null) {
        //noinspection unchecked
        return (Converter<ResponseBody, T>) converter;
      }
    }

    ........
  }

同样Converter.Factory是接口Converter中的一个抽象类,所有的ConveterFactory必须要继承这个抽象类,如添加Gson解析
addConverterFactory(GsonConverterFactory.create()) ;

  • 注解解析
    注解的解析主要分析主要分为两个部分,一是对方法上的注解进行解析,另一部分是对方法参数的解析

    • parseMethodAnnotation(annotation);是对方法上注解的解析

    “`java

    private void parseMethodAnnotation(Annotation annotation) {
    if (annotation instanceof DELETE) {
    parseHttpMethodAndPath(“DELETE”, ((DELETE) annotation).value(), false);
    } else if (annotation instanceof GET) {
    parseHttpMethodAndPath(“GET”, ((GET) annotation).value(), false);
    } else if (annotation instanceof HEAD) {
    parseHttpMethodAndPath(“HEAD”, ((HEAD) annotation).value(), false);
    if (!Void.class.equals(responseType)) {
    throw methodError(“HEAD method must use Void as response type.”);
    }
    } else if (annotation instanceof PATCH) {
    parseHttpMethodAndPath(“PATCH”, ((PATCH) annotation).value(), true);
    } else if (annotation instanceof POST) {
    parseHttpMethodAndPath(“POST”, ((POST) annotation).value(), true);
    } else if (annotation instanceof PUT) {
    parseHttpMethodAndPath(“PUT”, ((PUT) annotation).value(), true);
    } else if (annotation instanceof OPTIONS) {
    parseHttpMethodAndPath(“OPTIONS”, ((OPTIONS) annotation).value(), false);
    } else if (annotation instanceof HTTP) {
    HTTP http = (HTTP) annotation;
    parseHttpMethodAndPath(http.method(), http.path(), http.hasBody());
    } else if (annotation instanceof retrofit2.http.Headers) {
    String[] headersToParse = ((retrofit2.http.Headers) annotation).value();
    if (headersToParse.length == 0) {
    throw methodError(“@Headers annotation is empty.”);
    }
    headers = parseHeaders(headersToParse);
    } else if (annotation instanceof Multipart) {
    if (isFormEncoded) {
    throw methodError(“Only one encoding annotation is allowed.”);
    }
    isMultipart = true;
    } else if (annotation instanceof FormUrlEncoded) {
    if (isMultipart) {
    throw methodError(“Only one encoding annotation is allowed.”);
    }
    isFormEncoded = true;
    }
    }

对于注解的解析主要是对各种注解进行判断在调用parseHttpMethodAndPath()方法或parseHeaders()方法
而在这两个方法中也是拿到注解的值并进行记录
  - parameterAnnotationsArray()是对方法参数的注解进行解析
   此段代码较长不再贴出源码,同样是更具不同的注解来做出不同的判断,并拿到注解的值进行保存

创建了callAdapter和 responseConverter以及对注解惊进行解析后就可以返回ServiceMathod对象了


### 2.2.4 OkHttpCall

该对象实现了 Call<T>接口,该接口提供了一系列的生命周期方法,通是继承了Cloneable接口

```java
public interface Call<T> extends Cloneable {

  Response<T> execute() throws IOException;
  void enqueue(Callback<T> callback);
  boolean isExecuted();
  void cancel();
  boolean isCanceled();
  Call<T> clone();
  Request request();
}





<div class="se-preview-section-delimiter"></div>

下面来看OkHttpCall的具体实现

final class OkHttpCall<T> implements Call<T> {

     .....
         //最终的调用需要依赖该对象
        private okhttp3.Call rawCall;

      OkHttpCall(ServiceMethod<T, ?> serviceMethod, Object[] args) {
        this.serviceMethod = serviceMethod;
       this.args = args;
      }

       @Override public OkHttpCall<T> clone() {
         return new OkHttpCall<>(serviceMethod, args);
       }


    @Override public void enqueue(final Callback<T> callback){
            .....
                 call = rawCall = createRawCall();
            call.enqueue(new okhttp3.Callback() {.....}
                         ......
    }

      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;
  }

}




<div class="se-preview-section-delimiter"></div>

对于网络的具访问是通过OkHttp的Call对象来实现

2.3.5 serviceMethod.callAdapter.adapt(okHttpCall);

以下以RxJavaAdapter的源码为例

final class RxJavaCallAdapter<R> implements CallAdapter<R, Object> {
    ......
     @Override public Object adapt(Call<R> call) {
              ResponseCallable<R> resultCallable = new ResponseCallable<>(call);

             Observable<?> observable;

              return observable;
     }
}




<div class="se-preview-section-delimiter"></div>
final class ResponseCallable<T> implements Callable<Response<T>> {
  private final Call<T> call;

  ResponseCallable(Call<T> call) {
    this.call = call;
  }

  @Override public Response<T> call() throws IOException {
    // Since Call is a one-shot type, clone it for each new caller.
    return call.clone().execute();
  }
}

ResponseCallable的Call方法在每次调用时都创建了一个新的Call实例

最终返回了observable对象,用户可以根据RxJava的语法来访问网络

3 总结

3 总结

这里写图片描述

Python网络爬虫与推荐算法新闻推荐平台:网络爬虫:通过Python实现新浪新闻的爬取,可爬取新闻页面上的标题、文本、图片、视频链接(保留排版) 推荐算法:权重衰减+标签推荐+区域推荐+热点推荐.zip项目工程资源经过严格测试可直接运行成功且功能正常的情况才上传,可轻松复刻,拿到资料包后可轻松复现出一样的项目,本人系统开发经验充足(全领域),有任何使用问题欢迎随时与我联系,我会及时为您解惑,提供帮助。 【资源内容】:包含完整源码+工程文件+说明(如有)等。答辩评审平均分达到96分,放心下载使用!可轻松复现,设计报告也可借鉴此项目,该资源内项目代码都经过测试运行成功,功能ok的情况下才上传的。 【提供帮助】:有任何使用问题欢迎随时与我联系,我会及时解答解惑,提供帮助 【附带帮助】:若还需要相关开发工具、学习资料等,我会提供帮助,提供资料,鼓励学习进步 【项目价值】:可用在相关项目设计中,皆可应用在项目、毕业设计、课程设计、期末/期中/大作业、工程实训、大创等学科竞赛比赛、初期项目立项、学习/练手等方面,可借鉴此优质项目实现复刻,设计报告也可借鉴此项目,也可基于此项目来扩展开发出更多功能 下载后请首先打开README文件(如有),项目工程可直接复现复刻,如果基础还行,也可在此程序基础上进行修改,以实现其它功能。供开源学习/技术交流/学习参考,勿用于商业用途。质量优质,放心下载使用。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值