Retrofit: Type-safe rest Client for Android &java

Source: Internet
Author: User

Retrofit: Type-safe REST Client for Android &java

Monday, May 5, 2014

21:11

Official website: http://square.github.io/retrofit/

GitHub Address: https://github.com/square/retrofit

JavaDocs Address: http://square.github.io/retrofit/javadoc/index.html

This essay is a translation of the official website tutorial, put out for everyone to reference!

Outline

@GET, @POST, @PUT, @DELETE, @HEAD

@Path: {ID}

@Query: Name=value

@QueryMap

@Body : Passing Objects

@FormUrlEncoded, @Field

@Multipart, @Part: typedfile Send File

@Headers, @Header

Requestinterceptor : Add Header via Interceptor

Callback (void return ),Observable: Async

Back to Response

Setconverter: Configure Gson, automatically with converter

Seterrorhandler: Setting error handling

Overview: Define your request API in a Java interface:

Public interface Githubservice {

@GET ("/users/{user}/repos")

List<repo> Listrepos (@Path ("user") String user);

}

It then generates an implementation of the interface through the Restadapter class.

Restadapter restadapter = new Restadapter.builder ()

. setEndPoint ("https://api.github.com")

. build ();

Githubservice service = restadapter.create (Githubservice.class);

You can then call the following:

list<repo> repos = Service.listrepos ("Octocat");

A . To make an HTTP request via annotations:

    1. URL parameter substitution and query parameter support (that is, ?name=value&... meaning)
    2. customizing for POJO class conversions (automatically converts responses to POJO classes,Gson)
    3. Multipart Request object and File upload support (the request contains multiple media types, slices, etc.)

Two . Request method:

Support GET,POST,PUT,DELETE,HEAD

    1. A normal request:

Request method: request via Annotations

General request

@GET("/users/list")

The request can be directly added to query Parameter:sort=desc

@GET("/users/list?sort=desc")

Parameters can be replaced by @path annotations and {name} syntax: ID

@GET("/group/{id}/users")

List<user> grouplist (@Path ("id") int groupId);

Request parameters can be added via @query: sort

@GET("/group/{id}/users")

List<user> grouplist (@Path ("id") int groupId, @Query ("sort") String sort);

Request parameters can be added in bulk via @querymap: Options

@GET("/group/{id}/users")

List<user> grouplist (@Path ("id") int groupId, @QueryMap map<string, string> options);

    1. Special requests:

by @Body You can send an object directly through the restadapter conversion

@POST("/users/new")

void CreateUser (@Body User user, callback<user> cb);

Send form-encoded data via @formurlencoded and @field annotations? Todo

@FormUrlEncoded

@POST("/user/edit")

User UpdateUser (@Field ("First_Name") string first, @Field ("Last_Name") string last);

Multipart request via @multipart and @part annotations

@Multipart

@PUT("/user/photo")

User UpdateUser (@Part ("photo") Typedfile photo, @Part ("description") typedstring description);

    1. Add Header

static Add mode

Add a single head

@Headers("cache-control:max-age=640000")

@GET("/widget/list")

List<widget> widgetlist ();

@Headers Multiple header information: can have duplicate names

@Headers({

"Accept:application/vnd.github.v3.full+json",

"User-agent:retrofit-sample-app"

})

@GET("/users/{username}")

User GetUser (@Path ("username") String username);

Adding headers dynamically

Add head dynamically: Authorization

@GET("/user")

void GetUser (@Header("Authorization") String Authorization, callback<user> Callback)

Add all information

If you want to add the head to all requests, you can pass the Requestintercepter class.

Requestinterceptor requestinterceptor = new Requestinterceptor () {

@Override

public void intercept (Requestfacade request) {

Request.addheader ("User-agent", "Retrofit-sample-app");

}

};

Restadapter restadapter = new Restadapter.builder ()

. setEndPoint ("https://api.github.com")

. Setrequestinterceptor (Requestinterceptor)

. build ();

    1. Synchronous asynchronous and Rx. Observable

there is a way to return the synchronization method

@GET("/user/{id}/photo")

Photo Getuserphoto (@Path ("id") int id);

The last method is callback<t>, which is the asynchronous request (T is the data to be returned)

@GET("/user/{id}/photo")

void Getuserphoto (@Path("id") int ID, callback<photo> CB);

Retrofit also integrates R small Java to support the return of a rx.observable to support asynchronous requests

@GET("/user/{id}/photo")

Observable<photo> Getuserphoto (@Path ("id") int id);

Three . return Object type: Can be returned by the function return type,Callback,Observable get

// return Back to object

@GET ( "/users/list" )

list<user> userlist ();

//via callback

@GET ( "/users/list"

void UserList (callback<list<user> > CB);

//via observable

@GET ( "/users/list"

observable<list<user>> userlist ();

Can return native Http Response: By returning Response

@GET ("/users/list")

Response userlist ();

@GET("/users/list")

void userlist (callback<response> CB);

@GET("/users/list")

Observable<response> userlist ();

Iv. . Restadapter configuration: Can be configured by default or can be customized

    1. config gson: Custom gson example

gson Gson = new Gsonbuilder ()

    .setfieldnamingpolicy (fieldnamingpolicy.lower_case_with_underscores)

    .registertypeadapter (Date.class, New Datetypeadapter ())

    .create ();

 

restadapter restadapter = new Restadapter.builder ()

    .setendpoint ("https://api.github.com")

    .setconverter (new Gsonconverter (Gson))

    .build ();

 

githubservice service = restadapter.create (githubservice.class);

    1. Returns the configuration of the data type (which can support XML): The default is JSON, or you can define convertor to support other return data formats such as XML, such as a default simplexmlconverter)

Restadapter restadapter = new Restadapter.builder ()

. setEndPoint ("https://api.soundcloud.com")

. Setconverter (New Simplexmlconverter ())

. build ();

Soundcloudservice service = restadapter.create (Soundcloudservice.class);

    1. custom converter : To implement converter interface is available.
    2. Custom Synchronization Request Error handler: ErrorHandler

class MyErrorHandler implements ErrorHandler {

   @Override public throwable handleError (retrofiterror cause) {

    response r = Cause.getresponse ();

    if (r! = null && r.getstatus () = = 401) {

       return new unauthorizedexception (cause);

    }

    return cause;

  }

}

 

restadapter restadapter = new Restadapter.builder ()

     .setendpoint ("https://api.github.com")

    . Seterrorhandler (New MyErrorHandler ())

    .build ();

Maven Integration:

<dependency>

<groupId>com.squareup.retrofit</groupId>

<artifactId>retrofit</artifactId>

<version>1.5.0</version>

</dependency>

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.