Android First Knowledge Retrofit

Source: Internet
Author: User

What is Retrofit?

Retrofit is a RESTful architecture of Android (Java) client implementation, based on annotations, providing JSON to POJO (Plain ordinary Java object, simple Java objects), POJO to JSON, network please (Post,get, Put,delete, etc.) encapsulation.

Since it is just a network Request encapsulation Library, now there are so many people already familiar with the network Request Encapsulation Library, why also introduce it, because Retrofit is a set of annotated network Request package Library, let our code structure more clear. It can parse JSON data directly into Java objects, and even support callback operations to handle different results.

To learn more about Retrofit, you can view the official documentation.

Enter the theme.

first, the integration

Currently I am using Androidstudio, then add the following references in the model's Build.gradle file:

Compile ' com.squareup.okhttp3:okhttp:3.2.0 ' compile ' com.squareup.retrofit2:retrofit:2.0.0-beta4 ' compile ' Com.squareup.retrofit2:converter-gson:2.0.0-beta3 '


Retrofit relies on okhttp, so it needs to be integrated okhttp
The data returned by the API is in JSON format, where I use Gson to parse the returned data. Please use the latest version of Gson

second, the returned data format

Using the data interface of Baidu API: Celebrity Quotes API

The API host address of this interface is:;
interfaces to be accessed: avatardata/mingrenmingyan/lookup;

Need a key equal to Apikey's header and a keyword equal to the famous name of the query keyword, and the request is a GET request.

The data format returned by accessing the API is as follows:

{    "total": 227,    "result": [        {            "famous_name": "The snow of the car",            "famous_saying": "Extraordinary simplicity, extraordinary clarity-- This is the most astonishing quality of genius's wisdom. "        },        {            " famous_name ":" Joe Delleyton ",            " famous_saying ":" Genius is often dull in social life and "        },        {            " Famous_ Name: "Hugo",            "famous_saying": "Dare to Collide Fate is genius"        },        {            "famous_name": "Carlisle",            "famous_saying": " Genius is the ability to resist pain before anyone else. "        },        {            " famous_name ":" Lincoln ",            " famous_saying ":" Brilliant genius disdain to walk a family walk. " He looked for areas that had not been exploited so far. "        }    ],    " Error_code ": 0,    " reason ":" Succes "}

third, Androidstudio plug-in Gsonformat

We create a Famousinfo data object based on the JSON data returned from the API above, and we can use the Androidstudio plugin Gsonformat to quickly and easily convert JSON data to Java objects.

Package;import Java.util.list;public class Famousinfo {/*{"total": 227, "re Sult ": [{" Famous_name ":" The snow of the car "," famous_saying ":" Extraordinary simplicity, extraordinary clarity--this is the most astonishing quality of genius wisdom. "        "}, {" Famous_name ":" Joe Delleyton "," famous_saying ":" Genius often appears dull in social life "}, {"Famous_name": "Hugo", "famous_saying": "Dare to Collide Fate is genius"}, {"Famous_name "Carlisle", "famous_saying": "The so-called genius, is more than anyone to resist the pain of the experience of the ability." "}, {" Famous_name ":" Lincoln "," famous_saying ":" Brilliant genius disdain to walk a family walk. " He looked for areas that had not been exploited so far. "}]," Error_code ": 0," Reason ":" succes "}*///the definition of the following variable is consistent with the name of the field in the interface private in    T total;    private int error_code;    Private String reason;    Private list<resultentity> result;        public static class Resultentity {private String famous_name; Private String Famous_sayiNg        public void Setfamous_name (String famous_name) {this.famous_name = Famous_name;        } public void Setfamous_saying (String famous_saying) {this.famous_saying = famous_saying;        } public String Getfamous_name () {return famous_name;        } public String getfamous_saying () {return famous_saying;    }} public int gettotal () {return total;    } public void Settotal (int total) { = total;    } public int Geterror_code () {return error_code;    } public void Seterror_code (int error_code) {this.error_code = Error_code;    } public String GetReason () {return reason;    } public void Setreason (String reason) {This.reason = reason;    } public list<resultentity> GetResult () {return result;    } public void Setresult (list<resultentity> result) {This.result = result; }}

Iv. process of realization

First, according to the official instructions, we need to create an interface to return to call, as follows:

Package;import;import Retrofit2. Call;import retrofit2.http.get;import retrofit2.http.header;import retrofit2.http.query;/** * Created by Lizhixian on 16/5/8. */public interface Ifamousinfo {    @GET ("/avatardata/mingrenmingyan/lookup")    call<famousinfo> Getfamousresult (@Header ("ApiKey") string ApiKey,                                     @Query ("keyword") string keyword,                                     @Query ("page") int page,                                     @Query ("Rows") int rows);}

Where the name of the parameter must be written to, refer to:

Here we are using retrofit to provide annotations to define the interface's
* @get After we fill in the need to access the corresponding interface address
* @Header used to add headers
* @Query used to add query keywords

Now that the interface is well defined, let's define the wrapper class for the retrofit network interface service :

package;import Android.content.context;import Retrofit2. Gsonconverterfactory;import Retrofit2. retrofit;/** * Created by Lizhixian on 16/5/8.    */public class Retrofitwrapper {private static retrofitwrapper instance;    Private Context Mcontext;    Private Retrofit Mretrofit; Public Retrofitwrapper () {mretrofit = new Retrofit.builder (). BASEURL (Constant.baseurl). Addconverte    Rfactory (Gsonconverterfactory.create ()). build (); } public static Retrofitwrapper getinstance () {if (null = = instance) {synchronized (retrofitwrapper.c            Lass) {instance = new Retrofitwrapper ();    }} return instance;    } public <T> T Create (final class<t> service) {return mretrofit.create (service); }}
after the wrapper class for the network service is defined, the model for the access is defined.
Package;import Android.content.context;import;import;import;import;import Retrofit2. call;/** * Created by Lizhixian on 16/5/8.    */public class Famousinfomodel {private static Famousinfomodel Famousinfomodel;    Private Ifamousinfo Mifamousinfo;    Public Famousinfomodel (Context context) {Mifamousinfo = Retrofitwrapper.getinstance (). Create (Ifamousinfo.class); public static Famousinfomodel getinstance (context context) {if (Famousinfomodel = = null) {Famousi        Nfomodel = new Famousinfomodel (context);    } return Famousinfomodel; /** * Query Interface * @param famousinforeq * @return * */Public call<famousinfo> querylookup (famousinf Oreq famousinforeq) {call<famousinfo> Infocall = Mifamousinfo.getfamousresult (FamousInfoReq.apiKey, FamousIn Foreq.keYword,, famousinforeq.rows);    return infocall; }}

v. How to use

After building the interface, you can use it!

Use is divided into four steps:

    • Create a Retrofit Object
    • Create a request to access the API
    • Send Request
    • Processing results
      The main code is as follows:
Package;import Android.os.bundle;import;import Android.util.log;import Android.view.view;import Android.widget.button;import Android.widget.EditText;import Android.widget.textview;import;import; Import;import Java.util.list;import butterknife. Bindview;import Butterknife. Butterknife;import Butterknife. Onclick;import Retrofit2. Call;import Retrofit2. Callback;import Retrofit2. Response;public class Mainactivity extends appcompatactivity implements view.onclicklistener{public final String tag=    This.getclass (). GetName ();    Private Famousinfomodel Famousinfomodel;    @BindView ( EditText Meditkeyword;    @BindView ( button mserachbtn;    @BindView ( TextView mtxtcontent; @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate(savedinstancestate);        Setcontentview (R.layout.activity_main);        Butterknife.bind (this);        Initview ();    Famousinfomodel = Famousinfomodel.getinstance (this);  }/** * Initialize view */private void Initview () {} @Override @OnClick ({}) public        void OnClick (view view) {LOG.D (TAG, "OnClick"); if (view.getid () = = {famousinfomodel.querylookup (InitParams ()). Enqueue (New Callback<famo Usinfo> () {@Override public void Onresponse (call<famousinfo> call, Response<fam Ousinfo> response) {if (response.issuccess ()) {famousinfo result = response.                        Body ();                            if (null! = result) {list<famousinfo.resultentity> entity = Result.getresult (); Mtxtcontent.settext ("1," +entity.get (0). getfamous_saying () + "\ n---" +entity.get (0). Getfamous_name ()+ "\ n 2," +entity.get (1). getfamous_saying () + "\ n---" +entity.get (1). Getfamous_name ()); }}} @Override public void OnFailure (call<famousinfo> call, Throwable t)        {                }            });        }} private Famousinforeq InitParams () {famousinforeq mfamousinforeq = null;        mfamousinforeq= new Famousinforeq ();        Mfamousinforeq.apikey= Constant.apikey;        Mfamousinforeq.keyword = Meditkeyword.gettext (). toString ();;        mfamousinforeq.rows=20;    return mfamousinforeq; }}

attached source code: Https://

This article references and borrows from the blog:

If you do not want to use annotations, please download the code on the above blog.

Finally, thank _xuhao for his dedication.

Android First Knowledge Retrofit

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.