Retrofit basic introduction and simple way to use

Source: Internet
Author: User

Type-Safe HTTP client for retrofit:android and Java.

Introduction:1.Retrofit Convert your HTTP API to Java interface
<span style= "FONT-SIZE:14PX;" >public interface Githubservice {  @GET ("Users/{user}/repos")  call<list<repo>> Listrepos (@ Path ("user") String user); </span>

2.Retrofit class to implement the Githubservice interface
<span style= "FONT-SIZE:14PX;" >retrofit Retrofit = new Retrofit.builder ()    . BASEURL ("https://api.github.com/")    . Build (); Githubservice service = retrofit.create (githubservice.class);</span>

3. Each call to create Githubservice can be synchronous or asynchronous to request a remote network server
<span style= "FONT-SIZE:14PX;" >Call<List<Repo>> repos = Service.listrepos ("Octocat");</span>

use annotations to describe HTTP requests:
1. Support URL parameter substitution and query parameters
2. Object is converted to the request body (for example, JSON, protocol buffer)
3.Multipart request body and file upload API Declaration:the interface method and its parameter annotations indicate how the request will be handled.

1.REQUEST Method (Request):
Each method must have a request method and a relative URL provided by an HTTP comment. There are five built-in comments: GET, POST, PUT, DELETE, and HEAD. The relative URL of the resource is specified in the note.

For example:
<span style= "FONT-SIZE:14PX;" > @GET ("users/list") </span>

You can also specify query parameters for the URL, for example:
<span style= "FONT-SIZE:14PX;" > @GET ("Users/list?sort=desc") </span>

2.URL Manipulation (URL operation):

the requested URL can be updated dynamically using the method substitution blocks and parameters. Replace with {}, which is an alphanumeric string, and the corresponding argument must use the same string as the @path comment.

For example:
<span style= "FONT-SIZE:14PX;" > @GET ("group/{id}/users") call<list<user>> grouplist (@Path ("id") int groupId);</span>

query parameters can also be added, for example:
<span style= "FONT-SIZE:14PX;" > @GET ("group/{id}/users") call<list<user>> grouplist (@Path ("id") int groupId, @Query ("sort") String Sort);</span>

For complex query parameter combinations, map can be used, for example:
<span style= "FONT-SIZE:14PX;" > @GET ("group/{id}/users") call<list<user>> grouplist (@Path ("id") int groupId, @QueryMap map<string , string> options);</span>

3.REQUEST Body (Request body):

An object can be specified as an @body annotation used by an HTTP request body, for example:
<span style= "FONT-SIZE:14PX;" > @POST ("users/new") call<user> createUser (@Body user user);</span>

The object will also be used in the retrofit instance to specify a converter transformation. If no converter is added, only requestbody can be used.

4.FORM Encoded and MULTIPART (forms and multiple forms):

method can also declare form-encoded and multipart data to be sent.

form-encoded Data sending when the @formurlencoded method exists, each key-value uses annotations @field contains the name and the object that provides the value, for example:
<span style= "FONT-SIZE:14PX;" > @FormUrlEncoded @post ("User/edit") call<user> UpdateUser (@Field ("first_name") String First, @Field ("Last_ Name ") String last);</span>

multiple requests are used when the @multipart exists method, the Declarations section uses @part annotations, for example:
<span style= "FONT-SIZE:14PX;" > @Multipart @put ("User/photo") call<user> UpdateUser (@Part ("photo") Requestbody photo, @Part ("description") Requestbody description);</span>

Multipart Parts uses a retrofit converter or they can implement requestbody to handle their own serialization.

5.HEADER manipulation (Processing request header):

you can set methods that use @headers to annotate static headers, for example:
<span style= "FONT-SIZE:14PX;" > @Headers ("cache-control:max-age=640000") @GET ("Widget/list") call<list<widget>> widgetlist ();< /SPAN>

multiple request headers, for example:
<span style= "FONT-SIZE:14PX;" > @Headers ({    "Accept:application/vnd.github.v3.full+json",    "User-agent:retrofit-sample-app"}) @GET (" Users/{username} ") Call<user> GetUser (@Path (" username ") String username);</span>

Note that the head does not cover each other. All headers with the same name will be included in the request.

a request header can be dynamically updated using @header annotations. @Header must provide the appropriate parameters. If the value is null, the header is ignored. Otherwise, ToString will be called back to this value, using its results, for example:
<span style= "FONT-SIZE:14PX;" > @GET ("User") call<user> getUser (@Header ("Authorization") String Authorization) </span>

need to be added to each request header can be specified with a okhttp intercept.

6.SYNCHRONOUS VS. Asynchronous (synchronous vs asynchronous):

a call instance can be executed synchronously or asynchronously, and each instance can be used only once, but using the Clone () method creates a new instance to be used.
In Android, the callback function executes on the main thread, and on the JVM virtual machine, the callback function takes place on the same threads to execute the HTTP request. Retrofit Configuration (config)Retrofit is a class of API interfaces that translates to callable objects. Retorfit will provide you with a sound default value for your platform but it allows customization.

Converters (Converter):

By default, retrofit can only deserialize the responsebody type in okhttp and it can only accept its @body requestbody type.

Converters can be added to other types of support, the following are 6 common serialization libraries:
<span style= "FONT-SIZE:14PX;" >Gson:com.squareup.retrofit2:converter-gson</span>
<span style= "FONT-SIZE:14PX;" >Jackson:com.squareup.retrofit2:converter-jackson</span>
<span style= "FONT-SIZE:14PX;" >moshi:com.squareup.retrofit2:converter-moshiprotobuf:com.squareup.retrofit2:converter-protobufwire: Com.squareup.retrofit2:converter-wiresimple Xml:com.squareup.retrofit2:converter-simplexmlscalars (Primitives, Boxed, and String): com.squareup.retrofit2:converter-scalars</span>
use of retrofit in basic configuration Itemsconfiguration Retrofit in Android studioin theGradle Adding dependencies:
Compile ' com.squareup.retrofit2:retrofit:2.1.0 '

If the parsing method used is Gson, add Converter-gson:
Compile ' com.squareup.retrofit2:converter-gson:2.1.0 '

Retrofit requires at least Java 7 or Android 2.3.

An example of a simple use of retrofit1. First aggregation on the application of the interface, identity card query:
Address: http://apis.juhe.cn/idcard/index?key= you apply for key&cardno=330326198903081211

2. To obtain the basic information of the individual according to the input ID number, then create the interface:
<span style= "FONT-SIZE:14PX;" >public interface Usercardnoservice {    //basic information Query    @GET ("/idcard/index")    call<inforbean> Getinforesult (@Query ("key") string key, @Query ("Cardno") string cardno);    Whether the information is leaking    @GET ("/idcard/leak")    call<leakbean> Getleakresult (@Query ("key") String Key, @Query ("Cardno" ) String Cardno);    Whether the ID card is lost    @GET ("/idcard/loss")    call<lossbean> Getlossresult (@Query ("key") String Key, @Query ("Cardno ") String Cardno);} </span>

3. Create the entity class, where the entity class is the basic information query:
<span style= "FONT-SIZE:14PX;" >public class Inforbean {/** * resultcode:200 * Reason: successful return * Result: {"area": "Zhejiang Province Wenzhou Pingyang", "Sex": "    Male "," Birthday ":" March 08, 1989 "} */public String ResultCode;    public String reason;    public int error_code;    /** * Area: Wenzhou Pingyang County, Zhejiang province * Sex: Male * birthday:1989 March 08 */public Resultbean result;        public static class Resultbean {public String area;        public String sex;        public String birthday;        Public String Getarea () {return area;        } public void Setarea (String area) {This.area = area;        } public String Getsex () {return sex;        public void Setsex (String sex) {this.sex = sex;        } public String Getbirthday () {return birthday;        } public void Setbirthday (String birthday) {this.birthday = birthday;      }} public String Getresultcode () {  return resultcode;    } public void Setresultcode (String resultcode) {this.resultcode = ResultCode;    } public String GetReason () {return reason;    } public void Setreason (String reason) {This.reason = reason;    } public int Geterror_code () {return error_code;    } public void Seterror_code (int error_code) {this.error_code = Error_code;    } public Resultbean GetResult () {return result;    } public void Setresult (Resultbean result) {This.result = result; }}</span>

4. Create class userinfoactivity for user information query, build retrofit instance provider, parse data, assign value to data:
<span style= "FONT-SIZE:14PX;" >public class Userinfoactivity extends appcompatactivity implements View.onclicklistener {public static final Strin    G TAG = "userinfoactivity";    Private EditText Metinput;    Private Button btnquery;    Private TextView Mtvarea;    Private TextView Mtvsex;    Private TextView Mtvbirthday;    Private LinearLayout Llinfo;    Private String Mcardno;    Private Context Mcontext;        @Override protected void OnCreate (@Nullable Bundle savedinstancestate) {super.oncreate (savedinstancestate);        Mcontext = Userinfoactivity.this;        Setcontentview (r.layout.base_layout);    Initview ();        } private void Initview () {metinput = (EditText) Findviewbyid (r.id.etinput);        Btnquery = (Button) Findviewbyid (r.id.btnquery);        Mtvarea = (TextView) Findviewbyid (R.id.tvarea);        Mtvsex = (TextView) Findviewbyid (r.id.tvsex);        Mtvbirthday = (TextView) Findviewbyid (r.id.tvbirthday); Llinfo = (linearlayout) findviEwbyid (R.id.ll_info);    Btnquery.setonclicklistener (this);        } @Override public void OnClick (View v) {Mcardno = Metinput.gettext (). toString (). Trim (); if (!mcardno.matches (Regexputils.user_card)) {Toast.maketext (Mcontext, "input is wrong, please re-enter!)        ", Toast.length_short). Show ();        } else {getnetdata (); }} private void Getnetdata () {//Build Rtrofit instance Retrofit Retrofit = new Retrofit. Builder (). BASEURL (Globalcontact.baseurl). Addconverterfactory (Gsonconverterfactory.create ()        ). build ();        Usercardnoservice Infoservice = retrofit.create (Usercardnoservice.class);        Call<inforbean> call = Infoservice.getinforesult (Globalcontact.key, Mcardno); Call.enqueue (New callback<inforbean> () {@Override public void Onresponse (Call<inforbean&gt ; Call, response<inforbean> Response) {log.i (TAG, "Onresponse: "+ response.body (). toString ());                    if (response.issuccessful ()) {llinfo.setvisibility (view.visible);                    The data is assigned Mtvarea.settext (Response.body (). Result.area);                    Mtvsex.settext (Response.body (). Result.sex);                Mtvbirthday.settext (Response.body (). Result.birthday);                } else {llinfo.setvisibility (view.gone);                }} @Override public void OnFailure (call<inforbean> call, Throwable t) {            LOG.I (TAG, "onfailure:" + t.tostring ());    }        }); }}</span>

A long time to hear that has been useless, and now very regret, Retrofit2.0 too strong.

Retrofit Official website

Retrofit Source












Retrofit basic introduction and simple way to use

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.