Introduction and example display of retrofit for network loading framework __retrofit

Source: Internet
Author: User
Tags throwable

Retrofit is a network service library developed by Square
The returned data returned by the HTTP protocol based API can be converted to Java objects for easy operation .

Public interface Netservice {
  @GET ("Server/{param}/api")//Request URL in Get (SERVER/{PARAM}/API) >>>> Note that the URL here is generally not a complete URL, but the latter part of the entire URL, generally there is a base_url> later

  //where the {} Surrounded by the part is an indefinite parameter >> by the following @path annotated to ("") Enclosing parameter designation 

  //note, the names of these two must be consistent {param}  -> ("param")

 //This is a method the return value is a call inside contains a list set, the collection is loaded with the person data 

/ It's easy to guess that call is a retrofit in making request/response processing

   call<list<person>> Getperson (@Path ("param") String name);

We are here to briefly mention the concept of call, although simple, but call is a very important concept.

By invoking the Retrofit2 execute (sync) or Enqueue (asynchronous) method,
Sends a request to a network server and returns a response (Response).

Here we have the interface defined >> we see how to use this interface

To create a retrofit instance by retrofit instance to generate an instance of our interface retrofit RETROFIT = new Retrofit.builder (). BaseURL ("https://www.tp.com/") 

It is clear that base_url. Build () is specified here.

Create an instance of our interface Netservice service = Retrofit.create (Netservice. Class);

With the example, I can simply call our defined method to get the data and return to our desired call<list<person>> Personscall = Service.getperson ("Mike"); We then call the appropriate method to perform the synchronization or asynchronous Personscall. Enqueue (The new callback<list<person>> () {//asynchronous request has a callback interface @Ov
                Erride public void Onresponse (response<list<person>> Response, retrofit retrofit) { List<person> userlist = Response.body (); 
This is the data we want @Override public void onfailure (Throwable t) {}}); /************************************************************/try {RESPONSE&LT;LIST&LT;PERSON&GT;&G T Response = Personscall. Execute ();
        The synchronization request returns the corresponding data directly list<person> pers= response.body (); } CATCH (IOException e) {e.printstacktrace (); }

Retrofit mainly describes our HTTP requests in the form of annotations:

1. To support the indefinite parameter designation in the address of the requested URL and the designation of the query parameter (which we will say later)

2. Support to convert objects to request body (Json,protocol buffers, etc.)

Protocol buffers is a data description language developed by Google, similar to XML that can serialize structured data for data storage and communication protocols. At this stage, the support of C + +, JAVA, Python and other three programming languages. You don't have to delve into something like JSON.

3. Support multipart request body and file upload,

When defining a request interface, the annotations and parameters on the method indicate how we are going to execute the request.

Each interface must use an HTTP annotation, which we indicate in the note * * * and the relative address of the access * *

//currently supported by five kinds of get, POST, put, DELETE, head

@GET ("Server/list") Request method Get, requested relative address server/list

//Of course we can also carry request parameters on our relative address,
@GET ("server/list?id=1213")

request an address URL action

Before I mentioned the note on the request written on the relative address of the location of the parameters I can go to the dynamic designation//There is also

a point we can specify query parameters >> query parameters. Let me explain

@GET ("Group/{id}/users")
call<list<user>> grouplist (@Path ("id") int groupId, @Query (" Sort ") String sort);

Request Parameters:

Request Body header information Settings

We can also set the header information of our request body

@Headers ("cache-control:max-age=640000")
@GET ("Widget/list
") before we define a request method. Call<list<widget>> widgetlist ();

@Headers ({
    "Accept:application/vnd.github.v3.full+json",
    "User-agent:retrofit-sample-app"
})
@ Get ("Users/{username}")
call<user> GetUser (@Path ("username") String username);


Note that all header information is not covered with each other, and all header information with the same name is added to the request

//The header information of a request body can also be changed dynamically through the @header annotation


@GET ("user") call
<User> GetUser (@Header ("Authorization") String Authorization)

//Note the name of the parameter specified in the note @Header must be correct,
// If there is no incoming data (authorization==null), the head is omitted, otherwise the ToString method of the parameter (authorization) is called to the string type and set to the corresponding parameter ("authorization") On

//If all requests need to specify a header information, we can pass Okhttp interceptor. To specify

Synchronous and asynchronous
Each interface instance can be executed asynchronously or synchronously, and each instance can be used only once, but we can create a new instance by cloning (invoking Clone ()), or we can use the

In Android, the requested callback interface executes in the Android main thread

In normal Java programs, the thread that recalls and executes an HTTP request is a unified thread

Retrofit the default settings are more robust to provide us with some of the ways that columns can be used, but we can also customize, here we do not narrate.

Data Conversion

By default, retrofit can only convert the HTTP message body to the type of the okhttp response body responsebody, and only the okhttp type of the request body is supported Requestbody

Here are six other types of conversions that are more commonly used

Gson:        com.squareup.retrofit2:converter-gson
Jackson:     com.squareup.retrofit2:converter-jackson
Moshi:       com.squareup.retrofit2:converter-moshi
protobuf:    com.squareup.retrofit2:converter-protobuf
Wire:        com.squareup.retrofit2:converter-wire simple
XML:  com.squareup.retrofit2: Converter-simplexml
scalars (Primitives, boxed, and String): Com.squareup.retrofit2:converter-scalars

Let's get lazy. Compare the commonly used JSON-type data
RETROFIT RETROFIT = new Retrofit.builder ()
    . BaseURL ("https://api.github.com")
    . Addconverterfactory (Gsonconverterfactory.create ())
    //This sentence allows the data to support the JSON type
    . Build ();


We can customize the conversion type only if we inherit from  the Converter.factory class to customize our own conversion method can be

The above we only understand the general principle of the retrofit, in the practical application of no use,

Let's look at a real example of the code

Using Okhttp+retrofit

Jar Package Support

dependencies {
    compile ' com.squareup.retrofit:retrofit:2.0.0-beta2 '
    compile ' Com.squareup.retrofit:converter-gson:2.0.0-beta2 '
    compile ' com.squareup.okhttp:okhttp:2.4.0 '

}
Create the JavaBean we need (the entity class for the data) public
class User implements Serializable {
    private String name;
    Private String Pass;

  Omit Get Set method
    @Override public
    String toString () {return
        "user{" +
                "name= '" + name + ' \ ' + '
                , p Ass= ' + Pass + ' \ ' +
                '} ';
    }

Create the request interface that we need public

interface UserService {
    @GET ("Useraction/{name}")//url specified dynamically by the incoming parameter in the method
    call< List<user>> GetUser (@Path ("name") String name);


Create a retrofit instance for various configurations retrofit RETROFIT = new Retrofit.builder (). BaseURL ("https://api.github.com")/Address Prefix. Addconverterfactory (gsonconverterfactory.create ())//Set Data conversion. Client (new Okhttpclient ()

)//Set the client type. Build (); 


The instance of the request interface is obtained from the retrofit instance userservice UserService = Retrofit.create (Userservice.class);
            Synchronous or asynchronous to get the data//This is an asynchronous fetch fetch to carry a callback interface Call.enqueue (new callback<list<user>> () {@Override  public void Onresponse (response<list<user>> Response, retrofit retrofit) {list<user> UserList = Response.body (); This is the data we want. @Override public void OnFailure (Throwable t) {}}
);
            This is the information to return the response directly from the synchronization fetch parameter try {response<list<user>> Response = Call.execute ();
        list<user> users = Response.body (); catch (IOException e) {e.printstacktrace ();

 }

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.