This article focuses on the use of Retrofit
website
A, definitions,
A type safe HTTP client request framework for Android and Java
The Retrofit is aRestfulHTTP network request framework encapsulation. The web request is actually done by OKHttp, while Retrofit is only responsible for encapsulating the web request interface
Add dependencies
Gradle way:
implementation 'com.squareup.retrofit2:retrofit:(insert latest version)'
The latest version is 2.9.0
Confuse the configuration
If you use the R8 compiler (the default for Gradle plugin versions 3.4.0 and above), no configuration is required. The compression and obfuscating rules are already packaged in the Jar and R8 interprets them automatically.
To use ProGuard, manually configure the following rules:
Retrofit rules
Okhttp rules
Okio rules
Four, frame use
4.1 examples
- Step 1: Convert the HTTP API to a Java interface
public interface WanAndroidService {
@GET("article/list/{index}/json")
Call<JsonObject> getArticles(@Path("index") int index);
}
Copy the code
- Step 2: Use Retrofit to generate the Java interface (corresponding to Step 1
WanAndroidService
The realization of the)
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://wanandroid.com/")
.addConverterFactory(GsonConverterFactory.create())
.build();
WanAndroidService wanAndroidService = retrofit.create(WanAndroidService.class);
Copy the code
- Step 3: Use the Java interface (
WanAndroidService
) to create aCall
Object,Call
Objects can make synchronous or asynchronous HTTP requests to the Web server
Call<JsonObject> articles = wanAndroidService.getArticles(0);
JsonObject body = articles.execute().body();
Copy the code
System.out.println(" response data: "+body);
Print result:
4.2 API Description
Retrofit handles request logic by annotating interface methods and parameters,
4.2.1 Request method
Each interface method must have an annotation specifying the request method and relative URL. Retrofit has a total of eight built-in request method annotations:HTTP
.GET
.POST
.PUT
.PATCH
.DELETE
.OPTIONS
and HEAD
. The relative URL of the request is specified by the annotation attribute
- Example:
@GET("users/list")
4.2.2 URL Configuration
The request URL can be dynamically modified by substituting blocks and parameters in the method. A replaceable block is made by{
and}
An alphanumeric string surrounded by symbols. The corresponding parameters must be used@Path
Annotation, and the value of the annotation property remains the same as the code block string
- Example 1:
@GET("article/list/{index}/json")
Call<JsonObject> getArticles(@Path("index") int index);
Copy the code
- Example 2:(add request parameters with @query annotation)
@GET("article/list/{index}/json")
Call<JsonObject> getArticles(@Path("index") int index, @Query("cid") int cid);
Copy the code
- Example 3:(complex parameter combinations can be made using a map collection)
@GET("article/list/{index}/json")
Call<JsonObject> getArticles(@Path("index") int index, @QueryMap Map<String,String> params);
Copy the code
4.2.3 Request body
use@Body
An annotation can specify an object as the request body
This object will be converted using the converter specified when the Retrofit instance is created, and will only be used by default if no converter is addedRequestBody
- Example:
@POST("user/login")
Call<JsonObject> login(@Body User user);
Copy the code
4.2.4 FORM ENCODED and MULTIPART
Methods can also be declared to sendfrom-encoded
andmultipart
data
Methods using@FromUrlEncoded
Annotations will be sent when modifiedfrom-encoded
The data. Each key pair uses a parameter object that contains the name and provides the value@Field
To annotate.
- Example:
@FormUrlEncoded
@POST("user/login")
Call<JsonObject> login(@Field("username") String username, @Field("password") String password);
Copy the code
Methods using@Multipart
When an annotation is decorated, a Multipart request is sent. Request Parts to use@Part
Annotations annotations
Multipart Parts handles the serialization of parameters using either one of the converters provided by Rotrofit or a custom implementation RequestBody
- Example:
@Multipart
@PUT("user/photo")
Call<User> updateUser(@Part("photo") RequestBody photo, @Part("description") RequestBody description);
Copy the code
4.2.5 Request Header Configuration
use@Headers
Static request headers can be set
- Example:
@Headers("Accept-Encoding: gzip, deflate")
@GET("article/list/{index}/json")
Call<JsonObject> getArticles(@Path("index") int index, @Query("cid") int cid);
@Headers({ "Accept: application/json,application/xml,application/xhtml+xml,text/html; Q = 0.9, image/webp, * / *; Q =0.8", "accept-encoding: gzip, deflate"})
@GET("article/list/{index}/json")
Call<JsonObject> getArticles(@Path("index") int index, @Query("cid") int cid);
Copy the code
- ⚠️ : Request headers do not overwrite each other. Any request header with the same name is included in the request
use@Header
Annotations can modify the request header dynamically. Must be@Header
If the parameter value is null, the Header is ignored, otherwise the toString result of the parameter value will be used as the request Header value
- Example:
@GET("article/list/{index}/json")
Call<JsonObject> getArticles(@Header("test") String test, @Path("index") int index);
Copy the code
Like request parameters, Map collections can be used for complex request headers
- Example:
@GET("article/list/{index}/json")
Call<JsonObject> getArticles(@HeaderMap Map<String, String> test, @Path("index") int index);
Copy the code
You need to add a request header parameter to each requestOkHttp interceptorimplementation
4.2.6 Synchronous VS asynchronous
call
Instances can be executed synchronously or asynchronously. Each instance can only be executed once, but is usedclone()
Method to recreate a usable instance
On Android devices, the asynchronous callback method will be executed in the main thread. On the JVM, asynchronous callback methods are executed in the thread that will request execution
5. Retorfit configuration
Retrofit is a class that converts API interfaces into callable objects. By default, Retrofit will provide reasonable defaults for the platform, while also allowing customization
5.1 Converter
By default, Retrofit can only deserialize Http responses toOkHttp
theResponseBody
Type, and for@Body
Can only acceptRequestBody
type
Support for other types can be achieved by adding converters. Retrofit provides similar modules that encapsulate several of the most popular serialization libraries for easy user use
- 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
- JAXB: com.squareup.retrofit2:converter-jaxb
- Scalars (primitives, boxed, and String): com.squareup.retrofit2:converter-scalars
The following isGsonConverterFactory
Class, generatedWanAndroidService
Interface implementation, usingGson
The library deserializes response data
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://wanandroid.com/")
.addConverterFactory(GsonConverterFactory.create())
.build();
WanAndroidService wanAndroidService = retrofit.create(WanAndroidService.class);
Copy the code
5.2. Custom Converter
We can easily customize converters if we need to communicate using apis in formats not supported by Retrofit (e.g. YAML, TXT, custom format), or need to use different libraries to support existing formats.
Custom mode: CreateConverer.Factory
Subclass, and pass in an instance of that subclass when building the adapter