Retrofit2 Source Code Analysis

Source: Internet
Author: User

Original link: http://bxbxbai.github.io/2015/12/13/retrofit2-analysis/

The company's recent projects in the network framework used is retrofit, with a lot of later think this framework is really good to use, and then took a little time to debug a bit of source code, think not only very good coding, and design this framework of ideas are very special, harvest a lot, decided to record down

The source analysis of this article is based on Retrofit 2.0, and Retrofit 1.0 has a larger difference , this article is divided into several parts: 0, Retrofit is what, 1, Retrofit How to use, 2, Retrofit the principle is what, 3, some summary

The following retrofit all mean retrofit 2

0 What is retrofit?

From the retrofit official website introduction:

A type-safe HTTP Client for Android and Java

Simply said it is an HTTP request tool, and Google developed volley features very similar, here are volley source parsing, but the use of very similar. Retrofit easier to use, volley use more primitive and consistent with the user's intuition, in fact, I think if the volley package for themselves can be as simple as retrofit use

About the use of volley, please poke the above volley source parsing links, here will not repeat the

1 Retrofit how to use

Although retrofit official website already explained, I still want to follow my idea to say how it uses

For example, you want to request such an API:

Https://api.github.com/repos/{owner}/{repo}/contributors

To see the contributors of a repo on GitHub, first you have to build an interface like this:

public interface GitHub {    @GET("/repos/{owner}/{repo}/contributors")    Call<List<Contributor>> contributors(        @Path("owner") String owner, @Path("repo") String repo);}

Then you also need to create an Retrofit object:

public static final String API_URL = "https://api.github.com";// Create a very simple REST adapter which points the GitHub API.Retrofit retrofit = new Retrofit.Builder() .baseUrl(API_URL) .addConverterFactory(GsonConverterFactory.create()) .build();

Then use this Retrofit object to create an GitHub object:

Create an instance of our GitHub API interface.GitHub github = retrofit.create(GitHub.class);// Create a call instance for looking up Retrofit contributors.Call<List<Contributor>> call = github.contributors("square", "retrofit");

Finally, you can use this Githb object to get the data:

//Fetch and print a list of the contributors to the Library.call.enqueue (new callback<list<contributor>> () { @Override public void onResponse< Span class= "Hljs-params" > (response<list<contributor>> Response) {for ( Contributor Contributor:response.body ()) {System.out.println (contributor.login +  "(" + Contributor.contributions +  @Override public void onfailure (Throwable t) {}});   

This is used in a way that looks different from the volley, and when you use volley you must first create an Request object, including the parameters of the method,url,url of the request, and a listener that requests success and failure, and then put the request RequestQueue in , the last Networkdispatcher requests the server to get the data. And Retrofit just create an interface on it, it's amazing!!

And I would say that in fact the two approaches are essentially the same, except that the framework describes the HTTP request in a different way . So, you can see that the Github interface above is actually Retrofit a description of an HTTP request.

2 Principle of retrofit

Volley describes an HTTP request that requires an object to be created, Request and executes the request by putting the request object in a queue for the network thread to handle.

How did retrofit do it? The answer is Java's dynamic proxy

Dynamic Agent

When I started looking at retrofit's code, I was puzzled by the following code:

Create an instance of our GitHub API interface.GitHub github = retrofit.create(GitHub.class);

I sent an interface class object to the Retrofit object Github , how do I return an Github object? In the create approach to see, there are few lines of code, but I think these lines of code is retrofit's subtle place:

/** Create An implementation of the API defined by the {@code Service} interface. */@SuppressWarnings ("Unchecked")Single-interface proxy creation guarded by parameter safety.Public <T>TCreate(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, 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); } return Loadmethodhandler (method). Invoke (args);});      

Look, the create method is important to return a dynamic proxy object. So here's the problem.

What is a dynamic agent?

Before I look at the retrofit code, I know that Java Dynamic Agent is a very important thing, such as a lot of use in the spring framework, but what is the use of it?

Java Dynamic Agent is Java development gives developers a possibility: when you want to invoke a method of a class, insert the code you want to execute

For example, before you perform an operation, you have to determine if the user is logged in, or you need to determine how much money exists in the person's account before you make a payment. In such a simple sentence, I believe that a person who does not know the technology can also understand what the Java Dynamic Agent is.

Why use dynamic proxies

You see the code above, the code to get the data is this sentence:

Create a call instance for looking up Retrofit contributors.Call<List<Contributor>> call = github.contributors("square", "retrofit");

The above github object is actually a dynamic proxy object, not a real Githb interface implements object, and when the github object calls the contributors method, the dynamic proxy method is executed (you'll know by debugging)

At this point, the dynamic agent has played its role, you seem to have called the contributors method, in fact, at this time retrofit to Github translate the interface into an HTTP request, that is, the object in the retrofit MethodHandler , this object contains:

    • Okhttpclient: A tool for sending network requests
    • Requestfactory: Similar to Volley Request , contains the URL of the HTTP request, header information, mediatype, method, and Requestaction array
    • Calladapter:http type of request return data
    • Converter: Data Converters

Well, simply put, retrofit Call<List<Contributor>> call = github.contributors("square", "retrofit"); generates an HTTP request for you after you call it, and then you send the request when you call the call.enqueue method, and then you can process the response data, which, in principle, is the case. If you want to go to the details, you can say a lot more.

3 Retrofit of source code analysis

Want to understand the details of retrofit, first look at the composition of retrofit source code:

    1. A retrofit2.http package, which is all annotations that define HTTP requests, such as,,,,, GET POST , and PUT DELETE Headers Path Query so on
    2. The rest of the retrofit2 package more than 10 classes and interfaces are all retrofit code, the code is really very small, very simple, because retrofit the network request this part of the function is given to Okhttp
Retrofit interface

I think you need to know what the following interface means

Callback<T>

This interface is the interface that the retrofit requests the data to return, only two methods

    • void onResponse(Response<T> response);
    • void onFailure(Throwable t);
Converter<F, T>

The main function of this interface is to parse the HTTP returned data into Java objects, mainly by XML, Gson, PROTOBUF, etc., you can Retrofit add the implementation you need to use when creating the object Converter (see the code to create the retrofit object above)

Call<T>

The main function of this interface is to send an HTTP request, retrofit the default implementation is OkHttpCall<T> that you can implement your own call class according to the actual situation, this design and volley HttpStack interface design ideas very similar, subclasses can be implemented based on HttpClient or HttpUrlConnetctionHTTP Request tool, This design is very plug-in, and flexible

CallAdapter<T>

As mentioned above, there is CallAdapter only one of the attributes, there is responseType a <R> T adapt(Call<R> call) method, the implementation of this interface class is also only one, DefaultCallAdapter . The main function of this method is to Call convert the object to another object, perhaps to support Rxjava to design this class.

Operation of the retrofit

Just now, the GitHub github = retrofit.create(GitHub.class); code returned a dynamic proxy object, and Call<List<Contributor>> call = github.contributors("square", "retrofit"); when the code was executed, an object was returned to OkHttpCall get the Call object to execute the HTTP request.

One of the following code executes a very complex process

When a contributors method is executed, retrofit is actually the object that executes the dynamic proxy InvocationHandler , and finally an MethodHandler object is created, which is important

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

The code above is to create an object with MethodHandler MethodHandler 4 objects in it

0. okhttpclient

This is the default generated by the retrofit

1. Requestfactory:

Through RequestFactoryParser.parse(method, responseType, retrofit); generation, the main function is to parse all the data of the entire HTTP request

The main principle is to parse an interface, such as the above Github interface, the result is to get the entire HTTP request all the information, but also through @Path and @Query annotations stitching URL

No, all the code is in the retrofit.RequestFactoryParser class.

2. Calladapter

Get CallAdapter The following code:

PrivateStatic Calladapter<?> Createcalladapter (method, Retrofit Retrofit) {Type returntype = Method.getgenericret Urntype ();if (Utils.hasunresolvabletype (returntype)) {throw utils.methoderror (method,  "method return type must not Inc Lude a type variable or wildcard:%s ", returntype); } if (returntype = void. Class) {throw utils.methoderror (method,  "Service methods Cannot return void. "); annotation[] annotations = method.getannotations (); try {return retrofit.calladapter (ReturnType, annotations);} catch (runtimeexception e) {//Wide exception range because Factories is user code. throw utils.methoderror (E, method,  "unable to create call Adapter for%s ", returntype); }}

You can add what you want when you create a retrofit object, CallAdapter and the way you get it CallAdapter is also obtained from the Retrofit object.

The default is DefaultCallAdapter almost no upper function, basically the same as the animation inside LinearInterpolator

3. Converter

Getting Converter The object is almost the same as the principle above

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

The purpose of creating these 4 objects is to execute the following code

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

This github.contributors("square", "retrofit"); is the returned Call object.

Finally, you call the Call object's execute() or enqueue(Callback<T> callback) method, you can send an HTTP request.

Only the former is synchronous, the latter is asynchronous, which means that retrofit provides both synchronous and asynchronous HTTP request Methods

You may think that I just send an HTTP request, do you want to do so many things not very "slow"? Wouldn't it be a waste of performance?

I think, first of all, the mobile phone processor frequency is very high, parsing this interface may take 1ms less time (I have not tested), in the face of an HTTP would need hundreds of MS, or even thousands of MS is not worth mentioning, and retrofit will cache the parsed request, Map<Method, MethodHandler<?>> methodHandlerCachein this object

4 Last

Retrofit a very ingenious use of annotations to describe an HTTP request, an HTTP request is abstracted into a Java interface, and then the dynamic agent of the Java dynamic, the interface annotation "translated" into an HTTP request, and finally execute the HTTP request

Retrofit has a lot of dependencies on Java reflection, in fact there are many details in the code, such as exception capture, throw and handle, a lot of factory design patterns (why so much use Factory mode?). )

Retrofit interface design is just right, when you create Retrofit objects, let you have more flexible way to deal with your needs, such as using different, Converter use different CallAdapter , which also provides you use Rxjava to call retrofit possible

I also slowly read the Picasso Retrofit code, the harvest is still a lot of, but also more in-depth understanding of interface-oriented programming method, the code is good code is to rely on the interface rather than the implementation of the best example

Good thanks to the open source world, so I can read the code of Daniel. I always thought it would be impossible for a person to write good code without reading a good code. What is good code? Like Picasso and Retrofit This is good code, strong extensibility, low coupling, plug-in



Wen/Baiwali (Jane book author)
Original link: http://www.jianshu.com/p/c1a3a881a144
Copyright belongs to the author, please contact the author to obtain authorization, and Mark "book author".

Retrofit2 Source Code Analysis

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.