An article to easily master Retrofit2

Preface:
Reference Article

① Overview

What is Retrofit

  • Retrofit is a popular network request framework. It can be understood as an enhanced version of okhttp. The underlying package is Okhttp. To be precise, Retrofit is an encapsulation of a RESTful http network request framework . Because the network request work is essentially done by okhttp, and Retrofit is responsible for the encapsulation of the network request interface.

Essential process: App applications request the network through Retrofit, which essentially uses the Retrofit interface layer to encapsulate request parameters, Header, Url and other information, and then okhttp completes the subsequent request work. After the server returns the data, okhttp will hand over the original data to Retrofit, and Retrofit will analyze it according to user needs.

Pros of Retrofit

  • Super decoupling, interface definitions, interface parameters, and interface callbacks are no longer coupled together
  • Different httpClients can be configured to implement network requests, such as okhttp, httpclient
  • Support synchronous, asynchronous, Rxjava
  • Different deserialization tool classes can be configured to parse different data, such as json, xml
  • Fast request speed, easy to use, flexible and concise

② Annotation Introduction

Retrofit uses a large number of annotations to simplify requests. Retrofit abstracts okhttp requests into java interfaces, and uses annotations to configure and describe network request parameters.

1. Request method annotation

request method annotation illustrate
@GET get request
@POST post request
@PUT put request
@DELETE delete request
@PATCH patch request, which is a supplement to the put request and used to update local resources
@HEAD head request
@OPTIONS options request
@HTTP Through annotations, all the above annotations can be replaced, it has three attributes: method, path, hasBody

2. Request header annotation

request header annotation illustrate
@Headers It is used to add a fixed request header, and multiple ones can be added at the same time. The request headers passed through this annotation will not overwrite each other, but co-exist
@Header Passed in as a parameter of the method, used to add an unfixed header, it will update the existing request header

3. Request parameter annotation

Request parameter annotation illustrate
@Body It is mostly used for Post requests to send non-expressive data. According to the conversion method, the instance object is converted into a corresponding string to pass parameters. For example, using Post to send Json data, adding GsonConverterFactory is to convert the body into a json string for transmission
@Filed It is mostly used to pass parameters in Post mode, and it needs to be used in conjunction with @FromUrlEncoded, that is, to pass parameters in the form of a form
@FiledMap It is mostly used for form fields in Post requests and needs to be used in conjunction with @FromUrlEncoded
@Part For form fields, Part and PartMap are used in combination with the @multipart annotation, suitable for file uploads
@PartMap For form fields, the default accepted type is Map<String,RequestBody>, which can be used to upload multiple files
@Path Used for placeholders in Url
@Query Parameters used in Get requests
@QueryMap Similar to Query, used to determine form parameters
@Url Specify the request path

4. Request and response format (tag) annotations

Markup Class Annotations illustrate
@FromUrlCoded Indicates that the request sends encoded form data, and each key-value pair needs to be annotated with @Filed
@Multipart Indicates a request to send form_encoded data (used in scenarios where files are uploaded), each key-value pair needs to be annotated with @Part, and subsequent objects need to provide values
@Streaming Indicates that the response is returned in the form of a byte stream. If no annotation is used, all data will be loaded into memory by default. This annotation is especially useful when downloading large files

③ Use of basic annotations

@Get basic annotation

@GET("blog/{id}") //这里的{id} 表示是一个变量
Call<ResponseBody> getBlog(/** 这里的id表示的是上面的{id} */@Path("id") int id);

@Http full name annotation

/**
 * method 表示请求的方法,区分大小写,retrofit 不会做处理
 * path表示路径
 * hasBody表示是否有请求体
 */
@HTTP(method = "GET", path = "blog/{id}", hasBody = false)
Call<ResponseBody> getBlog(@Path("id") int id);

@Post

/**
 * {@link FormUrlEncoded} 表明是一个表单格式的请求(Content-Type:application/x-www-form-urlencoded)
 * <code>Field("username")</code> 表示将后面的 <code>String name</code> 中name的取值作为 username 的值
 */
@POST("/form")
@FormUrlEncoded
Call<ResponseBody> testFormUrlEncoded1(@Field("username") String name, @Field("age") int age);

/**
 * Map的key作为表单的键
 */
@POST("/form")
@FormUrlEncoded
Call<ResponseBody> testFormUrlEncoded2(@FieldMap Map<String, Object> map);

@Headers and @Headers

@GET("/headers?showAll=true")
@Headers({
    
    "CustomHeader1: customHeaderValue1", "CustomHeader2: customHeaderValue2"})
Call<ResponseBody> testHeader(@Header("CustomHeader3") String customHeaderValue3);

@Headers : Used on the method, add a fixed Header value when requesting

@Header : Can only be used in method parameters, and Header parameters can be passed dynamically

@Query and @QueryMap

/**
 * 当GET、POST...HTTP等方法中没有设置Url时,则必须使用 {@link Url}提供
 * 对于Query和QueryMap,如果不是String(或Map的第二个泛型参数不是String)时
 * 会被默认会调用toString转换成String类型
 * Url支持的类型有 okhttp3.HttpUrl, String, java.net.URI, android.net.Uri
 * {@link retrofit2.http.QueryMap} 用法和{@link retrofit2.http.FieldMap} 用法一样,不再说明
 */
@GET //当有URL注解时,这里的URL就省略了
Call<ResponseBody> testUrlAndQuery(@Url String url, @Query("showAll") boolean showAll);

When Url is not set in annotations such as @GET, POST...HTTP, you must use @Url in method parameters to provide Url

@Query and @QueryMap will be automatically used as parameters to splice Url

@Body

@POST("blog")
Call<Result<Blog>> createBlog(@Body Blog blog);

When there are many parameters, one is to use the @FieldMap annotation, and the other is to use @Body to pass an object. When the object is used as a parameter, a converter needs to be configured in Retrofit, such as the following, which will automatically convert the object Perform a conversion and pass it in the body of the request

Retrofit retrofit = new Retrofit.Builder()
        .baseUrl("http://localhost:4567/")
        //可以接收自定义的Gson,当然也可以不传
        .addConverterFactory(GsonConverterFactory.create(gson))
        .build();

Guess you like

Origin blog.csdn.net/qq_45408390/article/details/127500356