Use the exact words of the project: type-Safe HTTP client in Android and Java
Project Address: Https://github.com/square/retrofit
Here retrofit also needs to import its Gson dependent library, because the returned data needs to be gson to handle
1. Get request
2. Post request
3, single, multi-file upload
Demonstrates the provided interface (this interface does not support post mode)
Get request (supports normal request)
Get request (supports key-value pair parameters)
Post request (supports key-value pair parameters)
Post request (supports getting the returned string)
Post requests (uploading files and parameters)
Retrofit requests are sent as rest requests, so the encapsulation of the tool requires two things to do
- Encapsulation of the API for rest requests
- Retrofit's own package
As the JSON data returned by our interface is as follows
So here we need to encapsulate the bean object for the data we need to parse.
Retrofit uses annotations to declare get requests, post requests, request parameters, request first-class network access, and the following are the meanings of each annotation's representation
GET request related
- @Get: Send a Get request
- @Query: Get Request parameters
- @QueryMap: GET request Map parameter
POST request related
- @Post: Send a Post request
- @FormUrlEncoded: Form-based, common with @post
- @Field: Post Request parameters
- @FieldMap: POST request map parameter
Header Request related
- @Headers: Send header information
- @Header: Header Information parameters
- @HeaderMap: The map parameter for header information
Path Request Correlation
- @Path: Access path, end access to [email protected] content inside the middle-aged women's clothing brand
After understanding the meaning, write the rest of the API, is actually the request interface, the following code to see the specific
Retrofit and Okhttp, created using the constructor pattern, using a singleton mode to prevent multiple objects from being used
The above code does three things.
- Bind request URL
- Using Gson to process the returned JSON data
- Create and return the rest Request API Interface Iserver
Below you can use the tool class to get this iserver, call the provided interface method
API interface creation, such as registration function, need to upload two ID card photos, this is my own server interface
- @PartMap: Indicates the upload of a parameter
- @Part: Indicates a list of files
Create two methods to assist PARTMAP and part creation
Here you can go back to the demo section at the beginning of the article, where the retrofitutils is used
Because the file upload is I do the project when the use of the tool class is missing the content of the file upload, you can copy the code on their own
Use and encapsulation of Android combat--retrofit2