Retrofit2 source

本来一开始是用中文写的,写着写着,可能写代码写多了,赶脚英文好亲切,就换成英文了,

这也是我第一次写英文博客,曾经感觉遥不可及,but ,现在我也可以做到,哈哈哈哈,当然参考了白大神的博客,明天在整理一下,就酱,

欢迎各位大神指点~~~感激不尽

How to use it

Trilogy

create the Call interface. Like this @GET()Call <List<Bean>> contributors @Path("") String **;

create a retrofit object .

Retrofit retrofit = new Retrofit.Builder()

.baseUrl(API_URL)

.addConverterFactory(GsonConverterFactory.create())

create an Github object(using retrofit object)

To get the data(using github)

To compare with volley

volley:http request -> create a request object - > runing -> RequestQueue -> NetworkDispatcher Request to the server for data

create a request(include method,url,url param,success listener ande fail listener)

Put the request in the requestQueue

NetworkDispatcher Request to the server for data

volley Can be encapsulated into retrofit

principle

Dynamic proxy (compared to the request of the volley and implementation, can understand the retrofit using interface to request)

Github github = retrofit.create(Github.class);

Descendants through retrofit object making the class object of the interface,return github object

Enter the create method:

 @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 {http://write.blog.csdn.net/postedit/51356768
            // 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 serviceMethod = loadServiceMethod(method);
            OkHttpCall okHttpCall = new OkHttpCall<>(serviceMethod, args);
            return serviceMethod.callAdapter.adapt(okHttpCall);
          }
        });
  }

create() returns a Dynamic Proxy objects

What‘s the Dynamic Proxy

是这样一种类:它是在运行时生成的class,在生成它时必须提供一组interface给它,然后该class就宣称它实现类这些interface

Such as you want to perform an operation before judge whether this user login, or to determine the account how much money before payment

why use it?

just see that,

Call<List<Contributor>> call = github.contributors("square", "retrofit");

github -> Dynamic Proxy,It not a true Github interface implements object..

when github object call contributors method, execution is the Dynamic Proxy method

You look is to call the method of contributors,actually the Retrofit in fact at this time interface into an HTTP request, -> the  MethodHandler object

The MethodHandler object include

OkHttpClient: send the request of the tool

RequestFactory: similar to the Request of Volley, contains the urls, the HTTP Request Header information, MediaType, Method and RequestAction array

CallAdapter: HTTP request returns the type of dataThe (RxJava)

Converter: data ConverterWen

Trilogy

Call<List<Controbutor>> call = github.contributors(....)  ->  generate an Http request

call.enqueue ->send the request

handle the Response data

Source code analysis

composition

  1. retrofit2.http
  2. interface and class

The retrofit take over all this part of the function network request okHttp

interface

  • Callback<T>:

    • The request data returned by the interface
    • tow method
      1. void onResponse(Response<T> response);
      2. void onFailure(Throwable t)
  • Converter<F,T>:
    • HTTP return data parsed into Java objects. Such as xml,Gson,protobuf....
    • tip: Create Retrofit object added as you need to use the Converter to realize. Such as addConverterFactory(GsonConverterFactory.create())
  • Call<T>
    • send the HTTP request, like HttpStack(Volley) Interface design ideas
    • Retrofit the default implementation is OkHttpCall< T >
    • you can implement your own Call class according to actual condition
    • subclasses can be implemented based on HttpClient or HttpUrlConnetction HTTP request tool
  • CallAdapter<T>
    • an attribute -> responseType
    • an function -> <R> T adapter(Call<R> call)
    • an class implement -> DefaultCallAdapter: To convert the Call object to another object,such as rxjava

Run

return an Dynamic Proxy object: Github github = retrofit.create(Github.class)

return an OkHttpCall object: Call<List<T>> call = github.contributors("...","...")

You got the Call object to perform HTTP requests

contributors

When performing the contributors(): the Retrofit is carried out dynamic proxy InvocationHandler object, finally Will eventually create a MethodHandler object

static MethodHandler<?> create(Retrofit retrofit, Method method) {
    CallAdapter<Object> callAdapter = (CallAdapter<Object>) createCallAdapter(method, retrofit);
    Type responseType = callAdapter.responseType();
    Converter<ResponseBody, Object> responseConverter =
        (Converter<ResponseBody, Object>) createResponseConverter(method, retrofit, responseType);
    RequestFactory requestFactory = RequestFactoryParser.parse(method, responseType, retrofit);

    return new MethodHandler<>(retrofit.client(), requestFactory, callAdapter, responseConverter);
}

MethodHandler

an MethodHandler include four object

  1. OkHttpCliet

    • The default
  2. RequestFactory
    • Through RequestFactoryParser. parse (methord, responseType,retrofit) main effect is all the data parsing the Http request
    • Main principle is to parse an interface, such as the dead simple interface, the result is get the whole Http request all the information, can also through @ Path and @ Query annotation splicing Url
  3. CallAdapter
    • Create a Retrofit object, add the CallAdapter you want, and get CallAdapter way is also obtained from the Retrofit object
  4. Converter
    • private static Converter<ResponseBody, ?> createResponseConverter(Method method,
        Retrofit retrofit, Type responseType) {
        Annotation[] annotations = method.getAnnotations();
        try {
          return retrofit.responseBodyConverter(responseType, annotations);
        } catch (RuntimeException e) { // Wide exception range because factories are user code.
          throw Utils.methodError(e, method, "Unable to create converter for %s", responseType);
        }
      }
      

purpose

Object invoke(Object ... args){

return callAdapter.adapt(new OkHttpCall<>(client,requestFactory,responseConverter,args));}

This is dead simple. Contributors (" square ", "retrofit");Return to the Call object

Synchronous or asynchronous

finally you call Call object of the execute() or enqueue(Callback<T> callback) ,you can send an Http request

cache

Retrofit will cache the parsed request, is on the Map "Method, MethodHandler <?> > methodHandlerCache this object

Finally

Retrofit use annotations to describe an HTTP request

a HTTP request abstract into a Java interface,

and then use the Java dynamic proxy approach

dynamic to the interface of annotations "translate" into an HTTP request,

and then execute the HTTP request

retrofit  dependent on Java reflection, such as abnormal capture, throwing and processing,

and a large number of Factory design pattern

This code is good code is dependent on the interface rather than to realize the best example

时间: 2024-10-10 18:19:09

Retrofit2 source的相关文章

Retrofit2实现App自动更新

原理 Retrofit2和okhttp实现了apk的下载 自定义类实现Retrofit2的Callback类在里面通过IO流写入文件并且使用RxBus订阅下载进度 自定义类实现okhttp3的ResponseBody类并且在里面使用RxBus发布下载进度信息 在Service中使用Retrofit在后台下载文件 发送Notifaction到通知栏前台界面展示进度情况 实现步骤 1.创建UpdateManger管理类 这个类主要写了两个管理更新和弹框的方法. /** - 检测软件更新 */ pub

Retrofit2.0通俗易懂的学习姿势,Retrofit2.0 + OkHttp3 + Gson + RxJava

Retrofit2.0通俗易懂的学习姿势,Retrofit2.0 + OkHttp3 + Gson + RxJava Retrofit,因为其简单与出色的性能,也是受到很多人的青睐,但是他和以往的通信框架还是有点区别,不过放心,因为他本身还是挺简单的,所有我相信你看完这篇文章,对基本的请求是没什么问题的,其实现在网上这样的文章也有很多了,好了,那我们直接开车吧! 一.相关资料 Github:https://github.com/square/retrofit 官网文档:http://square

Retrofit2.0实践记录

前言 Type-safe HTTP client for Android and Java by Square, Inc. 官网:http://square.github.io/retrofit/ API:http://square.github.io/retrofit/2.x/retrofit/ 参考:http://gank.io/post/56e80c2c677659311bed9841 http://blog.csdn.net/lmj623565791/article/details/51

Retrofit2文件上传下载及其进度显示

序 前面一篇文章介绍了Retrofit2的基本使用,这篇文章接着介绍使用Retrofit2实现文件上传和文件下载,以及上传下载过程中如何实现进度的显示. 文件上传 定义接口 1 2 3 @Multipart @POST("fileService") Call<User> uploadFile(@Part MultipartBody.Part file); 构造请求体上传 1 2 3 4 5 File file = new File(filePath); RequestBod

Retrofit2 简明教程(一)

Retrofit2 简明教程(一) 相信大家都听过Retrofit的大名但是没有实际运用,或是已经运用过Retrofit1.x,因为Retrofit1.x和Retrofit2.x差别非常大,Retrofit1.x教程也是非常多,为了简单易懂,所以本文将以最新Retrofit2实践运用满足我们的Retrofit日常开发,后续我们也会更深入的了解Retrofit2,最后在本文中的尾页将附上Demo. 在阅读过程中有任何问题,请及时联系.如需转载请注明 fuchenxuan de blog Retro

网络通信框架Retrofit2

网络通信框架Retrofit2 1 概要 Retrofit2的简介以及特点 Retrofit2使用配置(导包,权限等) Retrofit2中常用的注解介绍 Retrofit2实现http网络访问 GET与POST请求 同步请求和异步请求 Retrofit2实现文件上传 Retrofit2进行大文件下载 2 Retrofit2的特点及简介 简介 Retrofit翻新,改型,改良 Retrofit是针对于Android/Java的.基于okHttp的.一种轻量级并使用注解方式和动态代理的网络请求框架

Retrofit2源码分析

例子 从简单的例子开始分析Retrofit2是怎么和其他的库一起合作的, 下边是一个很简单的例子,是rxjava2 + retrofit2 + okhttp3 + gson混合使用,是访问淘宝的ip地址查询服务,返回信息输出到EditText里. public static Retrofit getRetrofit() { if (retrofit == null) { synchronized (Retrofit.class) { if (retrofit == null) { retrofi

Retrofit2的GsonConverterFactory.create()和RxJava2CallAdapterFactory.create()的实现过程以及执行过程

一概述 上一节分析了retrofit2从创建到执行的完整流程,本节分析一下两个非常重要的功能.数据转换器的实现以及网络请求适配器的实现. 二.GsonConvertFactory.create()数据转换器的实现过程以及执行过程 我们先看下GsonConvertFactory.crete()的源代码,此类在retrofit-converters插件中 public final class GsonConverterFactory extends Converter.Factory { //创建G

Java注解(3)-注解处理器(编译期|RetentionPolicy.SOURCE)

注解的处理除了可以在运行时通过反射机制处理外,还可以在编译期进行处理.在编译期处理注解时,会处理到不再产生新的源文件为止,之后再对所有源文件进行编译. Java5中提供了apt工具来进行编译期的注解处理.apt是命令行工具,与之配套的是一套描述"程序在编译时刻的静态结构"的API:Mirror API(com.sun.mirror.*).通过Mirror API可以获取到被注解的Java类型元素的信息,从而提供自定义的处理逻辑.具体的处理工具交给apt来处理.编写注解处理器的核心是两个