Retrofit First Knowledge

Source: Internet
Author: User

Retrofit

Retrofit is a restful architecture of Android (Java) client implementations, based on annotations, providing JSON to POJO (Plain ordinary Java object, simple Java objects), POJO to JSON, network requests ( Post,get,put,delete, etc.) package.

Related information:

RESTful Baidu Encyclopedia

RESTful API Design

Retrofit principle

Retrofit Simple to use

Retrofit GitHub Project Address

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 that listRepos accesses the server's path through an HTTP GET request /users/{user}/repos and encapsulates the returned result as a List<Repo> Java object return.

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

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

new RestAdapter.Builder()    .setEndpoint("https://api.github.com")    .build();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

1. 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 , and HEAD . The parameter in the annotation is the relative URL path of the request.

@GET("/users/list")

URL parameters can also be specified in the URL path

@GET("/users/list?sort=desc")
2. URL Processing

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

@GET("/group/{id}/users") //注意 字符串idList<User> groupList(@Path("id") int groupId); //注意 Path注解的参数要和前面的字符串一样 id

Query parameters are also supported

@GET("/group/{id}/users")List<User> groupList(@Path("id") int groupId, @Query("sort") String sort);
3. 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.

4, 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.

5. Asynchronous VS Synchronization

Each function can be defined as asynchronous or synchronous.

5.1. A function with a return value for synchronous execution
@GET("/user/{id}/photo")Photo listUsers(@Path("id") int id);
5.2. 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")void listUsers(@Path("id") int 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.

6. Server results converted to Java objects

Use the Restadapter Converter to convert the HTTP request result (default to JSON) to a Java object, which is specified by the function return value or the callback interface.

// 通过返回值指定要转换的Java的对象的类型@GET("/users/list")List<User> userList();
// 通过Callback的泛型参数来制定要转换的Java对象的类型@GET("/users/list")void userList(Callback<List<User>> cb);
7. If you want to get directly the object returned by HTTP, use the Response object.
// 通过返回值的方式指定@GET("/users/list")Response userList();
// 通过Callback的泛型参数指定@GET("/users/list")void userList(Callback<Response> cb);
8. Important knowledge points involved in retrofit
    • Dynamic Agent
    • Annotations
    • Handler + MessageQueue + Thread + looper mechanism
    • Okhttp Request Network
    • Gson used to convert Java Pojo and parse JSON

Retrofit First Knowledge

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.