"Open Source Project 12" Retrofit–java (Android) Rest Interface Encapsulation Class Library

Source: Internet
Author: User

Retrofit Official Website: http://square.github.io/retrofit/

Retrofit is similar to the ORM concept in the Java World, where ORM transforms structured data into Java objects, and Retrofit transforms the data returned by the rest API into Java objects for ease of operation. It also encapsulates the invocation of network code.

For example:

 Public Interface Githubservice {  @GET ("/users/{user}/repos")  List<Repo> listrepos (@Path ("User" ) String user);

Define one of the rest API interfaces above. The interface defines a function Listrepos that accesses the server's/users/{user}/repos path through an HTTP GET request and encapsulates the returned result as a list<repo> Java object.

Where the value of {user} in the URL path is the value of the parameter user in the Listrepos function.

Then through RestAdapter the class to generate an GitHubService interface implementation;

Githubservice service = Restadapter.create (githubservice.  Class);

Once the implementation of the interface is obtained, the interface function can be called to interact with the server;

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

As can be seen from the above example, Retrofit uses annotations to declare HTTP requests

    • Support for URL parameter substitution and query parameters
    • The returned result is converted to a Java object (the returned result can be JSON, protocol buffers)
    • Support for multipart requests and file uploads
Specific use of documentation

Annotations on function and function parameters declare the request method

Request Method

Each function must have an HTTP annotation to indicate how the request was requested and the URL path of the request. There are 5 HTTP annotations in the class library:,,,, GET POST PUT DELETE andHEAD。 注解中的参数为请求的相对URL路径。

@GET ("/users/list")

URL parameters can also be specified in the URL path

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

URL Handling

The requested URL can be dynamically updated based on the function parameters. A replaceable chunk is a { string that is used and } surrounded, and the function parameter must be @Path annotated with annotations, and the parameter of the annotation is the same string

// Note the string ID int // Note that the parameters of the path annotation are the same as the previous string ID

Query parameters are also supported

@GET ("/group/{id}/users") Listint groupId, @Query ("sort") String sort);

requesting body (request body)

@Bodyannotations allow you to declare an object to be sent to the server as a request body.

@POST ("/users/new")void createUser (@Body user user, callback<user> CB);

The object will be converted to a RestAdapter string using the corresponding converter, or the byte stream is committed to the server.

Form encoded and MULTIPART forms and MULTIPART

Functions can also be annotated to send form data and multipart data

Use @FormUrlEncoded annotations to send form data, and use @Field annotations and parameters to specify the value of the Key,value parameter for each table item.

@FormUrlEncoded @post ("/user/edit") User UpdateUser (@Field ("first_name") String First, @Field (" Last_Name ") String last);

Use @Multipart annotations to send multipart data. Use @Part annotations to define each file that you want to send.

@Multipart @put ("/user/photo") User UpdateUser (@Part ("photo") Typedfile photo, @Part ("description" ) typedstring description);

The Multipart part uses RestAdapter a converter to convert, or it can be implemented TypedOutput to handle serialization on its own.

Asynchronous VS Synchronization

Each function can be defined as asynchronous or synchronous.

Functions that have a return value are executed synchronously.

@GET ("/user/{id}/photo") Photo ListUsers (@Path (int id);

The asynchronous execution function does not return a value and requires the last argument of the function to be a callback object

@GET ("/user/{id}/photo")voidint ID, callback<photo> CB);

On Android, the callback object is called in the main (UI) thread. In a normal Java application, callback is called in a thread that requests execution.

Server results converted to Java objects

Converts the HTTP request result (by default, JSON) to a Java object using the Restadapter converter, and the Java object is defined by the function return value or the callback interface

@GET ("/users/list") List<User> userlist () @GET ("/users/list")void UserList (callback<list<user>> CB);

If you want to get directly the object returned by HTTP, use the Response object.

@GET ("/users/list") Response userlist (); @GET ("/users/list")void userlist (callback< Response> CB);

Project home: http://square.github.io/retrofit/

Reference project: http://square.github.io/okhttp/

Android Sample project: Https://github.com/goodev/RetrofitDemo

"Open Source Project 12" Retrofit–java (Android) Rest Interface Encapsulation Class Library

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