I am honored if this article has helped you, and sorry if I have wasted your time. I hope to use the simplest plain words to help people like me. If there is any mistake, please do point out, so as not to mislead you, also mislead me. This article from: www.jianshu.com/users/320f9… Thank you for your attention.

Statement: this article is reproduced from: blog.csdn.net/leilba/arti… I wonder why nobody sees something so good.

Retrofit: An open source product from Square that provides a type-safe REST client for Android applications. It is said that Internet requests are very fast. This is the official document (English) : square. Making. IO/retrofit /

Start the text.


1. Introduction

Retrofit can convert your HTTP API into a JAVA interface form. Such as:

public interface GitHubService {
  @GET("users/{user}/repos")
  Call<List<Repo>> listRepos(@Path("user") String user);
}
Copy the code

The Retrofit class generates an implementation of the corresponding interface. Such as:

Retrofit retrofit = new Retrofit.Builder()
    .baseUrl("https://api.github.com/")
    .build();

GitHubService service = retrofit.create(GitHubService.class);
Copy the code

Each Call object returned by the interface can communicate with a remote Web server for synchronous or asynchronous HTTP requests. Such as:

Call<List<Repo>> repos = service.listRepos("octocat");
Copy the code

Retrofit uses annotations to describe HTTP requests: 1. Substitution of URL parameters and support for Query parameters 2. Object to request body (e.g. JSON, protocol buffers, etc.) 3. Multiple request bodies and file uploads Note: This site is still expanding the new API for 2.0

2. API specification

Retrofit needs to annotate the interface’s request method and the method’s parameters to indicate how the request needs to be handled.

2.1 Request Methods Each method must have an HTTP annotation that identifies the request method and its relative URL. There are five built-in annotations: GET, POST, PUT, DELETE, and HEAD. The relative URL of the resource should be specified in the comment:

  @GET("users/list")
Copy the code

You can also write the query argument directly in the URL:

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

2.2 URL Manipulation THE URL of a request can be dynamically updated by substituting blocks and parameters of the request method. A replacement block is a string of numbers or letters wrapped around {}, and the corresponding method argument needs to be annotated with @path to the same string. Such as:

@GET("group/{id}/users")
Call<List<User>> groupList(@Path("id") int groupId);
Copy the code

Query parameters can also be added at the same time.

@GET("group/{id}/users")
Call<List<User>> groupList(@Path("id") int groupId, @Query("sort") String sort);
Copy the code

Complex Query parameters can be constructed using a Map

@GET("group/{id}/users")
Call<List<User>> groupList(@Path("id") int groupId, @QueryMap Map<String, String> options);
Copy the code

2.3 Request Body The @body annotation allows you to specify a method as the Body of an HTTP request

@POST("users/new")
Call<User> createUser(@Body User user);
Copy the code

This parameter object is converted by the Converter in the Retrofit instance. Only RequestBody can be used as a parameter if no Converter is added to the Retrofit instance.

**2.4 Form encode and Multipart ** methods can also be declared to send data of type form-encoded and multipart. Form-encoded data can be sent using the @formurlencoded annotation method. Each key-value pair needs to be annotated with the @filed key name, and subsequent objects need to provide values.

@FormUrlEncoded
@POST("user/edit")
Call<User> updateUser(@Field("first_name") String first, @Field("last_name") String last);
Copy the code

Mutipart requests can also be sent via the @multipart annotation method. Each section needs to be annotated with @Part.

@Multipart@PUT("user/photo")
Call<User> updateUser(@Part("photo") RequestBody photo, @Part("description") RequestBody description);
Copy the code

Multiple request parts need to use Retrofit’s Converter or implement their own RequestBody to handle their own internal data serialization.

You can set the request static Headers by using the @headers annotation.

@Headers("Cache-Control: max-age=640000")
@GET("widget/list")
Call<List<Widget>> widgetList();
Copy the code


@Headers({
    "Accept: application/vnd.github.v3.full+json",
    "User-Agent: Retrofit-Sample-App"
})
@GET("users/{username}")
Call<User> getUser(@Path("username") String username);
Copy the code

Note that header parameters do not overwrite each other; all header parameters with the same name are included in the request. Of course you can update the request Header dynamically with the @header annotation. A corresponding argument must be provided to the @header annotation. If the value is null, the header argument is ignored. Otherwise, the toString method of the value will be called and the result of the call will be used.

@GET("user")
Call<User> getUser(@Header("Authorization") String authorization)
Copy the code

Of course, you can use the OkHttp interceptor to specify every required header parameter.

2.6 Synchronous VS Asynchronous You can execute instances synchronously or asynchronously. Each example can only be used once, but you can use clone() to create a new instance that can be used. In the Android environment, callback will be executed in the main thread; In a JVM environment, the callback will be executed in the same thread as the Http request.

3. The Retrofit configuration

Retrofit classes are converted to callable objects through apis you define. By default, Retrofit returns you reasonable defaults, but also allows you to specify them.

By default, Retrofit can only deserialize the HTTP Body to the OKHttp ResonseBody type and can only accept the RequestBody type as @body. The addition of converters can be used to support other types. The following six sibling modules use common serialization libraries for your convenience.

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

The following provides an example of implementing gson deserialization using the GsonConverterFactory class to generate an interface for GitHubService.

Retrofit retrofit = new Retrofit.Builder()
    .baseUrl("https://api.github.com")
    .addConverterFactory(GsonConverterFactory.create())
    .build();

GitHubService service = retrofit.create(GitHubService.class);
Copy the code

If you need to interact with an API that doesn’t use Retrofit’s content formats, or if you want to implement an existing format using a different library, you can easily create and use your own converter. You need to create a class that inherits from Converter.Factory and add it to the instance when you build the adapter.

4. Download

Left Latest JAR

Source code, examples, and website are available on GitHub

4.1 the maven

< the dependency > < groupId > com. Squareup. Retrofit2 < / groupId > < artifactId > retrofit < / artifactId > < version > 2.0.0 < / version > </dependency>Copy the code

4.2 gradle

The compile 'com. Squareup. Retrofit2: retrofit: 2.0.0'Copy the code

Retrofit supports minimum Java7 and Android 2.3

4.3 Obfuscation If code obfuscation is used in your project, you need to add the following lines to your configuration

-dontwarn retrofit2.**
-keep class retrofit2.** { *; }
-keepattributes Signature
-keepattributes Exceptions
Copy the code