Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Example Analysis of Retrofit Source Code

2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article mainly introduces the Retrofit source code example analysis, has a certain reference value, interested friends can refer to, I hope you can learn a lot after reading this article, the following let Xiaobian take you to understand.

Introduction to basic use

Before introducing the source code, let's take a look at the basic use of Retrofit, get a general understanding of the process, and follow this process to analyze the source code so that it won't be messy.

1. Initialize the Retrofit object

Retrofit retrofit = new Retrofit.Builder () / / use the custom mGsonConverterFactory .addConverterFactory (GsonConverterFactory.create ()) .baseUrl ("http://apis.baidu.com/txapi/") .build ())

2. Define the interface

Public interface APi {@ GET ("hello/world") Call getNews (@ Query ("num") String num,@Query ("page") String page);}

3. Initiate a network request

MApi = retrofit.create (APi.class); Call news = mApi.getNews ("1", "10"); news.enqueue (new Callback () {@ Override public void onResponse (Call call, Response response) {} @ Override public void onFailure (Call call, Throwable t) {}})

Retrofit essential analysis

Seeing the whole process above, I must have looked confused if I didn't explore the source code. I defined an interface and specified the return value. Why can I use this interface directly? What about the implementation of the interface? Can I write a random return value without specifying the return Call line? Despite these questions, we can roughly guess what Retrofit does.

Guess: Retrofit mainly creates an instance for the interface we define, and then this instance calls the method in the API to assemble the value we defined in the annotation into the information needed to initiate the http request, and finally uses this information to generate an object specified in the return value of the interface, which can be used to initiate the real request.

To put it simply, Retrofit is to spell the things in the annotation into the object of the http request, and then the object initiates the request.

Verify the guess

Who implemented this interface?

When initiating a network request, there is a sentence:

MApi = retrofit.create (APi.class)

Obviously, the implementation of the interface should be done by this create. Let's go in and take a look at the source code:

Public T create (final Class 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, @ Nullable 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 serviceMethod = (ServiceMethod) loadServiceMethod (method); OkHttpCall okHttpCall = new OkHttpCall (serviceMethod, args); return serviceMethod.adapt (okHttpCall);}})

Here we don't have to look at some details, just focus on what we want to know, what this Create method does, see Proxy.newProxyInstance, oh! It is obvious that the reason why the interface can be called directly is that the dynamic proxy technology is used to produce a proxy object. Binggo, a problem solved!

When did you start assembling the parameters in the comments into the information requested by http?

What does a dynamic agent do? (you'd better learn the dynamic agent of Java alone, which is sometimes very useful. There are a lot of materials on the Internet.)

Dynamic proxies are generally used to intercept methods so that they can do their own things before or after the execution of a method. Reviewing the use of Retrofit, the defined method is called directly after the proxy object is generated by the Create method. Then, all the small actions must be done when the interface method is called. Specifically, the method in invoke

If (method.getDeclaringClass () = = Object.class) {return method.invoke (this, args);} if (platform.isDefaultMethod (method)) {return platform.invokeDefaultMethod (method, service, proxy, args);} ServiceMethod serviceMethod = (ServiceMethod) loadServiceMethod (method); OkHttpCall okHttpCall = new OkHttpCall (serviceMethod, args); return serviceMethod.adapt (okHttpCall)

The first two if judgments are mainly to skip some of the methods built into object and object, except for these, all the remaining methods must be defined in the interface, that is, what we want to intercept. Then what really works is three sentences:

ServiceMethod serviceMethod = (ServiceMethod) loadServiceMethod (method); OkHttpCall okHttpCall = new OkHttpCall (serviceMethod, args); return serviceMethod.adapt (okHttpCall)

The loadServiceMethod () method is used to assemble the http request information, and this problem is solved!

How to generate the object that initiates the http request?

After the above analysis, OkHttpCall okHttpCall = new OkHttpCall (serviceMethod, args); this is clearly used to produce this object.

How do I convert the object to the return value we specified in the interface?

To explain here, when we defined the interface before, it was like this:

GET ("hello/world") Call getNews (@ Query ("num") String num,@Query ("page") String page)

The Call here is actually very similar to Okhttp's Call, and even the method is almost the same, but this can be defined when Retrofit and Rxjava are used together.

@ GET ("book/search") Observable getSearchBook (@ Query ("Q") String name, @ Query ("tag") String tag, @ Query ("start") int start, @ Query ("count") int count)

The return value specified here is no longer Call, but becomes the Observable of RxJava, so there must be a step to convert the previously assembled information into the object we specify, and the core is done by serviceMethod.adapt () on the last line.

Thank you for reading this article carefully. I hope the article "sample Analysis of Retrofit Source Code" shared by the editor will be helpful to everyone. At the same time, I also hope that you will support and pay attention to the industry information channel. More related knowledge is waiting for you to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report