Use of Retrofit (1) and retrofit
This article is not original, but probably translated the English documentation of Alibaba fit, and the right is your own note.
Http://square.github.io/retrofit/ address:
1. Introduction
Retrofit converts your http api to a Java API.
1 public interface GitHubService {2 @GET("/users/{user}/repos")3 Call<List<Repo>> listRepos(@Path("user") String user);4 }
Retrofit generates an implementation class for the GithubService interface.
1 Retrofit retrofit = new Retrofit.Builder()2 .baseUrl("https://api.github.com")3 .build();4 5 GitHubService service = retrofit.create(GitHubService.class);
Each Call sent from the generated GitHubService can send a synchronous or asynchronous HTTP request to a remote Web server.
1 Call <List <Repo> repos = service. listRepos ("octocat ");
Use annotations to describe HTTP requests:
- Supports URL parameter replacement and Request Parameters
- Supports converting objects into request bodies (e.g., JSON, protocol buffers)
- Supports multiple request bodies and file uploads.
2. API Declaration
The Annotations and its parameters on the interface method indicate how the request is processed.
A. Request Method
Each method must have an HTTP annotation that provides the request method and releative URL. Retrofit has five built-in annotations:GET
,POST
,PUT
,DELETE
, AndHEAD. In annotation
The relative URL is specified.
1 @ GET ("/users/list ")
You can also specify the Request Parameters in the URL.
1 @ GET ("/users/list? Sort = desc ")
B. URL Processing
A request URL can be dynamically replaced by the replacement block and parameters in the method. The replacement block is a string containing letters or numbers wrapped in. The corresponding parameter must be an identical string with @ Path. That is:
1 @GET("/group/{id}/users")2 List<User> groupList(@Path("id") int groupId);
The query parameters can also be added.
1 @GET("/group/{id}/users")2 List<User> groupList(@Path("id") int groupId, @Query("sort") String sort);
Complex query parameters can be combined into a Map.
1 @GET("/group/{id}/users")2 List<User> groupList(@Path("id") int groupId, @QueryMap Map<String, String> options);
C. Request body
An object with the @ Body annotation can be used as an HTTP request Body.
1 @POST("/users/new")2 Call<User> createUser(@Body User user);
This object can be converted by the converter specified by Retrofit. If not specified, it can only be used in RequestBody.
D. Form Encoded and Multipart
Methods can also be declared to send form-encoded and MutiPart data.
When using form-encoded, add @ on Method @FormUrlEncoded
Annotation. Use @ for each key-Value Pair @Field
Annotation package key. That is:
1 @FormUrlEncoded2 @POST("/user/edit")3 Call<User> updateUser(@Field("first_name") String first, @Field("last_name") String last);
When multiple requests are used, add @ on Method @Multipart annotation, used for each part@Part
Add declaration. That is:
1 @Multipart2 @PUT("/user/photo")3 Call<User> updateUser(@Part("photo") RequestBody photo, @Part("description") RequestBody description);
Use multiple requestsRetrofit converter or
Self-implementedRequestBody
Process your own serialization.
E. Request Header manipulation
You can use @Headers
Sets a static Request Header for a request method.
1 @Headers("Cache-Control: max-age=640000")2 @GET("/widget/list")3 Call<List<Widget>> widgetList();
1 @Headers({2 "Accept: application/vnd.github.v3.full+json",3 "User-Agent: Retrofit-Sample-App"4 })5 @GET("/users/{username}")6 Call<User> getUser(@Path("username") String username);
Note that Headers of the same name are not overwritten and all Headers with the same name are included in the request.
The @ Headers annotation can be used to dynamically update the Headers of a request. You must set a letter or Number Parameter for @ Headers. If the actual value is null, the request header is ignored. Otherwise, the toString () method is called and used in the request.
1 @GET("/user")2 Call<User> getUser(@Header("Authorization") String authorization)
Headers that need to be added to every request can be specified using an OkHttp interceptor.
F. synchronous VS. asynchronous
The Call instance can be executed synchronously or asynchronously. Each instance can only be used once. If you do not use the clone () method, you can create another instance that can be used.
In Android, callback is executed in the main thread. In JVM, callback is executed in the same thread that initiates an HTTP request.
3. Configure the fit parameter
Retrofit is a class that converts a callback object through your API. Elastic fit provides you with the default configuration, but also allows you to customize the configuration.
A. Converter
By default, container fit can only be used to serialize HTTP bodies to the ResponeBody type of OkHttp. For @ Body, only the ResponeBody type can be received.
The following types can also be supported:
- Gson:
com.squareup.retrofit:converter-gson
- Jackson:
com.squareup.retrofit:converter-jackson
- Moshi:
com.squareup.retrofit:converter-moshi
- Protobuf:
com.squareup.retrofit:converter-protobuf
- Wire:
com.squareup.retrofit:converter-wire
- Simple XML:
com.squareup.retrofit:converter-simplexml
B. Custom Converter
You can also inheritConverter.Factory
Class custom converter, and then input this class instance when creating the adapter.
4. Integration Method
Click here for the latest jar package.
Alibaba fit source code and sample programs On Github.
Maven
<dependency> <groupId>com.squareup.retrofit</groupId> <artifactId>retrofit</artifactId> <version>(insert latest version)</version></dependency>
Gradle
compile 'com.squareup.retrofit:retrofit:(insert latest version)'
Environment required by Retrofit: Java 7 or above and Android 2.3 or above.
ProGuard
1 -dontwarn retrofit.**2 -keep class retrofit.** { *; }3 -keepattributes Signature4 -keepattributes Exceptions