Android Network Framework Retrofit2.0 Introduction, use, and encapsulation

Source: Internet
Author: User
Tags representational state transfer browser cache


Today, Android's network framework is no longer as ubiquitous as it was before, and as Google httpclient it out, it seems to mean Android is getting more mature. The best volley in the network framework are no longer so glamorous, instead of Retrofit and okHttp.
It feels like the departure of the white beard in onepiece symbolizes the change of the Times, the beginning of the new era, the collapse of Dover symbolizes the ban of seven Wu Hai system, will not use Retrofit + OkHttp + Rxjava A series of technology, will not enter the threshold of a new era, Nor is it enough to be called a qualified developer.

Haha gossip not much to say, just on the Android platform to develop such a long time of a little feeling. Everybody, look at the smile and forget it. Let's introduce Retrofit. (Skip 1.9 directly)

All the code in this article is Retrofitlearn;

1. Retrofit Introduction

A type-safe HTTP Client for Android and Java
A type-safe network framework for Android and Java platforms

Retrofit is a type-safe REST client for Android built by Square. The library provides a powerful framework for authenticating and interacting with APIs and sending network requests with O Khttp.
Retrofit is a square-developed type-safe Rest Android client request library. This library provides a powerful framework for network authentication, API requests, and sending network requests with okhttp.

Retrofit transforms the data returned by the rest API into Java objects, and, like the ORM Framework, transforms the stored data in the database into the corresponding Java bean object.

So we know that retrofit is a type-safe network framework, and it uses rest APIs, so let's look at what rest is.

2. REST Introduction:

Resources representational State Transfer
State transformation of resource presentation layer

    • Each URI represents a single resource
    • Between the client and the server, a presentation layer that passes this resource (the "resource" is presented in a concrete form, such as. txt,.png,.jpg)
    • The client uses four HTTP verbs (get is used to get resources, post is used to create or update resources, put is used to update resources, delete is used to remove resources) to operate on server-side resources for "Presentation State transformation"

For rest, here are just a few of the conclusions, there are super good links at the end of the article, please check. If you are using the API is rest, then congratulations, such an API looks really comfortable, fortunately, we are using the rest API.

Knowing what rest is, then we will begin to introduce the usage of retrofit.

3. Retrofit basic usage (not encapsulated)

1. Adding dependencies in Build.gradle


2. Create an interface, declare an API

//Retrofit turns your HTTP API into a Java interface.//创建接口,声明GitHub的APIpublicinterface GitHubAPI {     /*       请求该接口:     */     @GET("users/{user}")      Call<User> userInfo(@Path("user") String user);}

3. Call in the Mainactivity.oncreate () method

/*1. Initializing okhttpclient*/Okhttpclient client =NewOkhttpclient ();/*2. Creating retrofit*/Retrofit =NewRetrofit.builder ()//Set okhttpclient. Client (client)//Set BaseURL, note that baseurl must be suffix "/". BASEURL ("")//Add Gson converters. Addconverterfactory (Gsonconverterfactory.create ()). build ();/*2. Get GitHub's api*/Githubapi Githubapi = retrofit.create (Githubapi.class);/*3. Asynchronous calls * /call<user> Usercall = Githubapi.userinfo ("Baiiu"); Usercall.enqueue (NewCallback<user> () {@Override  Public void Onresponse(call<user> call, response<user> Response)        {User BODY = response.body (); LOGUTIL.D (BODY = =NULL?"BODY = = NULL": Body.tostring ()); }@Override  Public void onfailure(call<user> call, Throwable t) {/ * Determine if the Cancel has been dropped * /        if(Call.iscanceled ()) {LOGUTIL.D ("The call is canceled,"+ toString ()); }Else{LOGUTIL.E (t.tostring ()); }      }    });/ * Cancel call * ///usercall.cancel ();/* Synchronous invocation, for example, as follows (of course, cannot be called in the main thread): * ///each instance can only is used once, but calling clone () would create a new instance that can be<user> clone = Usercall.clone (); response<user> Response = Clone.execute (); User BODY = Response.body (); LOGUTIL.D (BODY = =NULL?"BODY = = NULL": Body.tostring ());

1. Set BaseURL must suffix "/", such as , this article said super clear: Retrofit 2.0:the biggest update yet on the best HTTP Client Library for Android

2. Since retrofit passed in BaseURL at the time of creation, basically all requests are based on the BaseURL. But there are always some APIs that don't start with the BaseURL, especially if some companies may not be restful APIs. So what should we do? Retrofit provides an annotation to @Url address this issue, which can be accessed directly at run time directly using the URL. The code is as follows:

//使用@Url注解,传入该Url地址就OK啦,跨过BaseUrl,直接访问该Url地址@GET Call<Daily> getNewsList(@Url String url);

Well, next, knowing the basic use of retrofit, the next step is to introduce retrofit's annotations.

4. Retrofit Annotations

Retrofit uses annotations to declare how the API is requested, request parameters, and so on. Here is only a description of its @Header annotations, others please read the official website document and Yang Retrofit2 fully parse the relationship between exploration and okhttp. (This piece of writing is also translated official documents and reference hung-like, will lengthen space)

The settings for the request header can be @Header added with annotations, and there are two ways to add them:

    • Sets the static request header.
@headers ()  @get ( " Widget/list ")  call  <list<widget>> widgetlist  ();  @headers ({ "accept:application /vnd.github.v3.full+json ", " User-agent:retrofit-sample-app "})  @< Span class= "Hljs-function" >get ( "users/{username}" )  call  <user> GetUser  (@ path ( "username" )   String   username );  
    • Dynamically set the request header.
@GET("user")Call<User> getUser(@Header("Authorization"String authorization)

Note that headers does not overwrite all other . All headers with the same name is included in the request.
The settings of the same request header in different places will not be overwritten, but will be added to the request header.

Headers that need to being added to every the request can be specified using an OkHttp interceptor.
If you want to add the same header to each request, you can use the Okhttp Interceptor .

So, the next step is to introduce interceptor.

5.Interceptors Use

Retrofit 2.0 is forced to rely on okhttp, so all requests can be re-processed using the Okhttp interceptor interceptors.

Interceptors is a powerful mechanism that can monitor, rewrite, and retry calls.

When using, implement the Interceptor interface, do our own processing.
Currently in use, generally used, and 设置UA 设置缓存策略 打印Log so on. Here is an introduction to setting up the UA Interceptor:

1. Create a interceptor that sets the UA

 Public Final  class useragentinterceptor implements Interceptor {  Private Static FinalString User_agent_header_name ="User-agent";Private FinalString Useragentheadervalue; Public Useragentinterceptor(String Useragentheadervalue) { This. Useragentheadervalue = Useragentheadervalue; }@Override  PublicResponseIntercept(Chain Chain)throwsIOException {FinalRequest originalrequest = Chain.request ();FinalRequest requestwithuseragent = Originalrequest.newbuilder ()//Remove the previous default UA. Removeheader (User_agent_header_name)//Set UA. AddHeader (User_agent_header_name, Useragentheadervalue). Build ();returnChain.proceed (requestwithuseragent); }}

2. Set this interceptor when creating okhttpclient

new OkHttpClient.Builder()        //添加UA        .addInterceptor(new UserAgentInterceptor(HttpHelper.getUserAgent()))        //失败重连        .retryOnConnectionFailure(true)        //time out        .readTimeout(TIMEOUT_READ, TimeUnit.SECONDS)        .connectTimeout(TIMEOUT_CONNECTION, TimeUnit.SECONDS)        .build();

The use of interceptors and headers makes it easy to use the HTTP cache itself. This piece is more difficult to handle before using volley. The solution is to talk about the retrofit caching mechanism.

6. Configure the network cache

The most convenient way to use retrofit is that it provides caching (although this is the HTTP itself), and we can configure our own caching policies casually via headers and interceptor.

6.1 Cache Setting Principle:

The settings for the cache are achieved by setting the HTTP request header and the properties in the response header Cache-Control max-age . When the interceptor is replicated, the response head is set Cache-Control to achieve the goal. For a cache hit of HTTP itself, please check the link at the end of the article (HTTP is a big guy, after all).

6.2 Cache Setup Steps
    1. set the cache directory
      The retrofit itself is not cached by default, and even the cache directory does not provide a default, so to implement caching, you must set the cache directory when you create Okhttpclient. This super pit, oneself tried for half a day, finally looked under the cache over the source code, unexpectedly did not have the default cache directory!!!

    2. How to set the cache

      • set by adding @Headers("Cache-Control: max-age=120") . The request is added Cache-Control , retrofit will cache the returned data for the request by default.
      • Cache is implemented through interceptors.
6.3 Implementing Interceptor for caching

Two cache policies are provided (reference), and the application interceptor and Net interceptor are set when the cache is set:

    • Allcachedinterceptor
      There's no net. Cache, you can set the intermittent time.
      You can also set a separate cache time for a request and use the @Headers("Cache-Control: max-age=120") line.

    • Onofflinecachedinterceptor
      There is a network can not go cache, can set the time, set to 0 means that there is a network does not go cache, all refresh data, no net force to read the cached data.

So far, the basic usage and caching settings for retrofit have been understood, and the write-point example has been used, and the next step is to encapsulate it, making it easier to invoke.

7. Retrofit Package

Encapsulated retrofit is designed to provide more convenient invocation, better configuration and use. So see the beginning of the retrofit call method, there are probably so many steps:
1. Create Okhttpclient
2. Create a Retrofit instance
3. Get the API interface we wrote
4. Calling asynchronously in code

Then the package is sure to start with these steps:

7.1 Initialize Okhttpclient

Create a Okhttpfactory class, initialize the Okhttpclient, and provide a singleton for that instance externally. and provide a HttpHelper class to provide the required parameters, such as UA.
The advantage of this is that the program will use Okhttp to do some other request operations, such as downloading, uploading and other network operations, you can use a common okhttpclient.

Here, we use enumerations to generate a single case.

enumokhttpfactory {INSTANCE;Private FinalOkhttpclient okhttpclient;Private Static Final intTimeout_read = -;Private Static Final intTimeout_connection = -; Okhttpfactory () {//Print request logHttplogginginterceptor Interceptor =NewHttplogginginterceptor (); Interceptor.setlevel (HttpLoggingInterceptor.Level.BODY);//Cache directoryCache cache =NewCache (MyApplication.mContext.getCacheDir (),Ten*1024x768*1024x768); Okhttpclient =NewOkhttpclient.builder ()//Print request log. Addinterceptor (Interceptor)//stetho, you can view requests in chrome. Addnetworkinterceptor (NewStethointerceptor ())//Add UA. Addinterceptor (NewUseragentinterceptor (Httphelper.getuseragent ()))//must be set to cache directory. cache (Cache)//Go to cache, two must be set. Addinterceptor (NewOnofflinecachedinterceptor ()). Addnetworkinterceptor (NewOnofflinecachedinterceptor ())//Fail re-connect. Retryonconnectionfailure (true)//time out. ReadTimeout (Timeout_read, Timeunit.seconds). ConnectTimeout (Timeout_connection, Timeunit.seconds). Build (); } PublicOkhttpclientgetokhttpclient() {returnOkhttpclient; }}
7.2 Initializing Retrofit

Still create a singleton with an enumeration:

publicenum RetrofitClient implements ApiContants {  INSTANCE;  privatefinal Retrofit retrofit;  RetrofitClient() {    new Retrofit.Builder()        //设置OKHttpClient        .client(OKHttpFactory.INSTANCE.getOkHttpClient())        //baseUrl        .baseUrl(GITHUB_BASEURL)        //gson转化器        .addConverterFactory(GsonConverterFactory.create())        .build();  }  publicgetRetrofit() {    return retrofit;  }}
7.3 Creating the Apifactory class encapsulates all APIs

Title, create Apifactory class to manage all the API interface, to provide methods to obtain them, so that the call will be much easier, but also easy to modify.

publicenum ApiFactory {  INSTANCE;  privatefinal GitHubAPI gitHubAPI;  privatefinal AnotherAPI anotherAPI;  ApiFactory() {    gitHubAPI = RetrofitClient.INSTANCE.getRetrofit().create(GitHubAPI.class);    anotherAPI = RetrofitClient.INSTANCE.getRetrofit().create(AnotherAPI.class);  }  publicgitHubAPI() {    return gitHubAPI;  }  publicgetAnotherAPI() {    return anotherAPI;  }}

This can be a lot easier to package externally, such as:

    Call<User> userCall = ApiFactory.gitHubAPI().userInfo("baiiu");

Encapsulated code on GitHub: Retrofitlearn;

In this case, I think it is good, you can happily write code. Now let's talk about a magical tool.

8. Stetho A magical tool

First: use the tool to flip the wall. you can't go over the wall or use Charles.

    1. Added in Gradle:
  ‘com.facebook.stetho:stetho:1.3.1‘  ‘com.facebook.stetho:stetho-okhttp3:1.3.1‘
    1. Open Chrome, enter chrome://inspect
      Click on your program to inspect, you can use Chrome to grab the package, debug your app. But you can not turn over the wall, you will see a blank ...

After all, retrofit has been out for a long time, no hurry to use it. When it comes to using retrofit, deep down to its application of the HTTP mechanism, it really feels like a great app experience. With retrofit as the network framework, it can feel the beauty of its design, not to mention can be combined with Rxjava, the United States to not.

Reference: These references are worth a look at

  • A book about retrofit.
    Retrofit-basic Authentication on Android

  • Retrofit Introduction:
    Retrofit official website
    Simple HTTP with Retrofit 2
    Consuming APIs with Retrofit
    Retrofit2 the relationship between the full analytic exploration and the Okhttp
    Retrofit 2.0:the biggest update yet on the best HTTP Client Library for Android

  • Introduction to Restful APIs
    Understanding the RESTful architecture
    In Layman's Rest

  • OkHttp
    Effective okHttp
    Android okhttp Full parsing It's time to get to know okhttp.
    Android an improved Okhttp package library

  • Interceptors
    Wiki-interceptors Chinese

  • Configure caching
    RETROFIT2.0+OKHTTP3 caching mechanisms and the problems encountered
    Use retrofit and okhttp to implement network caching. No net read cache, network re-request based on expiration time
    Browser HTTP Caching Principle analysis
    Browser cache

  • Others that help to understand
    Four common ways of POST submission data

  • Stetho
    The process of solving provisional headers is shown

Android Network Framework Retrofit2.0 Introduction, use, and encapsulation

Related Article

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: 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.