Retrofit is a simple and powerful Android network request framework. It maps Http requests to Java methods through annotations, thereby simplifying the implementation process of network requests.
Advantages of Retrofit:
- Supports synchronous and asynchronous requests;
- Support HTTP methods such as GET, POST, PUT, DELETE;
- Support parameter splicing, header setting, file upload, download and other request methods;
- Data in formats such as JSON and XML returned by the server can be easily parsed.
Use of Retrofit:
-
Introduce dependencies: Add the following dependencies to the build.gradle file:
implementation 'com.squareup.retrofit2:retrofit:2.9.0' implementation 'com.squareup.retrofit2:converter-gson:2.9.0'
-
Define the API interface: define an interface that contains the request method, and use annotations to describe the method and parameters. The sample code is as follows:
public interface ApiService { // 请求方式 + 请求地址 @GET("api/login") // 方法参数 Call<User> login(@Query("username") String username, @Query("password") String password); }
-
Create a Retrofit instance: Create a Retrofit instance and specify the base URL. The sample code is as follows:
Retrofit retrofit = new Retrofit.Builder() .baseUrl("<https://www.example.com/>") .addConverterFactory(GsonConverterFactory.create()) .build();
-
Create an API instance: use Retrofit to create an API instance, the sample code is as follows:
ApiService apiService = retrofit.create(ApiService.class);
-
Send request: call the method in the API interface to send the request, the sample code is as follows:
Call<User> call = apiService.login("username", "password"); call.enqueue(new Callback<User>() { @Override public void onResponse(Call<User> call, Response<User> response) { // 请求成功回调 User user = response.body(); } @Override public void onFailure(Call<User> call, Throwable t) { // 请求失败回调 } });
Retrofit annotations
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 |
related reference
https://juejin.cn/post/6978777076073660429