Retrofit2使用和解析(一)
Retrofit是square公司开源的一个网络访问框架。它将网络请求全部封装起来了,相比较Volley来说更加简单,而且访问接口API更加符合Restful设计。当然Volley也不错哈。Retrofit的代码维护者包括大名鼎鼎的JakeWharton JakeWharton。
这篇文章主要是介绍Retrofit的使用方法。
Introduction
Retrofit turns your HTTP API into a Java interface.
Retrofit需要我们把接口访问的API都使用接口的形式。(Retrofit会在代码运行时进行检查)1
2
3
4public interface GitHubService {
@GET("users/{user}/repos")
Call<List<Repo>> listRepos(@Path("user") String user);
}
The Retrofit class generates an implementation of the GitHubService interface.
使用Retrofit Builder辅助生成Retrofit对象,进而(通过代理)创建接口实例。1
2
3
4
5Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://api.github.com/")
.build();
GitHubService service = retrofit.create(GitHubService.class);
Each Call from the created GitHubService can make a synchronous or asynchronous HTTP request to the remote webserver.
每次调用service的方法都会创建一个Call对象,通过这个Call对象来进行继续的操作。1
Call<List<Repo>> repos = service.listRepos("octocat");
Use annotations to describe the HTTP request:
- URL parameter replacement and query parameter support
- Object conversion to request body (e.g., JSON, protocol buffers)
- Multipart request body and file upload
API Declaration
Annotations on the interface methods and its parameters indicate how a request will be handled.
使用Annotations(标注)在接口的方法和参数上用来表明这个请求的处理方式。
Request Method
Every method must have an HTTP annotation that provides the request method and relative URL. There are five built-in annotations: GET, POST, PUT, DELETE, and HEAD. The relative URL of the resource is specified in the annotation.
每个接口的方法必须有一个HTTP annotation,retrofit提供了5个内置的annotations:GET, POST, PUT, DELETE, and HEAD。同时请求的url也必须指定在annotation里。1
2@GET("users/list")
@GET("users/list?sort=desc")
URL Manipulation
A request URL can be updated dynamically using replacement blocks and parameters on the method. A replacement block is an alphanumeric string surrounded by { and }. A corresponding parameter must be annotated with @Path using the same string.
- 请求的url可以使用参数和预留位置(block)来动态更新。需要替换的block使用{}预留位置。参数必须使用@Path和相同的字符串与之对应。
1
2@GET("group/{id}/users")
Call<List<User>> groupList(@Path("id") int groupId);
比如:
service.groupList(100)则访问
group/100/users
- Query parameters can also be added.
查询的参数也可以添加。1
2@GET("group/{id}/users")
Call<List<User>> groupList(@Path("id") int groupId, @Query("sort") String sort);
比如:
service.groupList(100,year)则访问
group/100/users?sort=year
- For complex query parameter combinations a Map can be used.
1
2@GET("group/{id}/users")
Call<List<User>> groupList(@Path("id") int groupId, @QueryMap Map<String, String> options);
Request Body
- An object can be specified for use as an HTTP request body with the @Body annotation.
java对象可以使用@Body指定http请求的body。(这个应该是只有POST/PUT请求才会有的)1
2@POST("users/new")
Call<User> createUser(@Body User user);
The object will also be converted using a converter specified on the Retrofit instance. If no converter is added, only RequestBody can be used.
Form Encoded and Multipart
Methods can also be declared to send form-encoded and multipart data.
Form-encoded data is sent when @FormUrlEncoded is present on the method. Each key-value pair is annotated with @Field containing the name and the object providing the value.1
2
3@FormUrlEncoded
@POST("user/edit")
Call<User> updateUser(@Field("first_name") String first, @Field("last_name") String last);
Multipart requests are used when @Multipart is present on the method. Parts are declared using the @Part annotation.1
2
3@Multipart
@PUT("user/photo")
Call<User> updateUser(@Part("photo") RequestBody photo, @Part("description") RequestBody description);
Multipart parts use one of Retrofit’s converters or they can implement RequestBody to handle their own serialization.
Header Manipulation
You can set static headers for a method using the @Headers annotation.1
2
3@Headers("Cache-Control: max-age=640000")
@GET("widget/list")
Call<List<Widget>> widgetList();
1 | @Headers({ |
Note that headers do not overwrite each other. All headers with the same name will be included in the request.
A request Header can be updated dynamically using the @Header annotation. A corresponding parameter must be provided to the @Header. If the value is null, the header will be omitted. Otherwise, toString will be called on the value, and the result used.1
2@GET("user")
Call<User> getUser(@Header("Authorization") String authorization)
Headers that need to be added to every request can be specified using an OkHttp interceptor.
Synchronous vs. Asynchronous
Call instances can be executed either synchronously or asynchronously. Each instance can only be used once, but calling clone() will create a new instance that can be used.
Call实例可以同步或异步执行。每个Call实例只能执行一次。可以使用clone()方法创建一个新的可用的实例。
On Android, callbacks will be executed on the main thread. On the JVM, callbacks will happen on the same thread that executed the HTTP request.
Retrofit Configuration
Retrofit is the class through which your API interfaces are turned into callable objects. By default, Retrofit will give you sane defaults for your platform but it allows for customization.
我们可以使用Retrofit来对Retrofit进行访问的配置。
添加gradle依赖
1 | compile 'com.squareup.retrofit2:retrofit:(insert latest version)' |
下一篇文章分析下Retrofit的源码。学习一下这个不足20个类的网络库。我们自己在以后写框架的时候也可以借鉴下。