Retrofit使用介绍

Retrofit通过Java接口和注解轻松地实现HTTP API的调用,下面以微博的开放API为例介绍

快速预览使用方式

声明接口和数据结构

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public interface WeiboAPI {

@GET("statuses/home_timeline.json")
Call<HomeTimelineResp> homeTimeline(@QueryMap Map<String, String> params);

// 一条微博的结构
public class Status {
public String id;
public String mid;
public String text;
@SerializedName("create_at")
public String createAt;
public String source;
// ...
}

public class HomeTimelineResp {
public List<Status> statuses;
}
}

创建Retrofit并调用接口

1
2
3
4
5
6
7
8
9
10
11
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://api.weibo.com/2")
// 解析依赖Gson,你也可以使用其他框架或自己的
.addConverterFactory(GsonConverterFactory.create())
.build();

WeiboAPI weiboAPI = retrofit.create(WeiboAPI.class);
Map<String, String> params = new HashMap<>();
params.put("access_token", accessToken);
List<Status> statusList = weiboAPI.homeTimeline(params).execute().statuses;
// ...

可以看出基础使用上非常简单

POST使用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public interface WeiboAPI {

...

// 评论微博
@POST("comments/create.json")
public Call<Status> createComments(@Body Map<String, String> body);

...

}

// 使用
Map<String, String> body = new HashMap<>();
body.put("access_token", accessToken);
Status status = weiboAPI.createComments(body).execute()

注解类型

网路请求:

  • @GET
  • @POST
  • @PUT
  • @DELETE
  • @HEAD
  • @PATH
  • @OPTIONS
  • @HTTP

参数:

  • @Header: 标注一个header字段
  • @Headers: 标注一组header字段
  • @URL: 标注请求的url
  • @Body: 标注请求体内容
  • @Path: 标注路径中的参数值
  • @Field: 标记Form中的一个字段
  • @FieldMap: 标记Form中的一组字段
  • @Part: 标记multipart请求中的一个part的内容
  • @PartMap: 标记multipart请求中的多个part的内容
  • @Query: 标记请求url中的一个query参数
  • @QueryMap: 标记请求url中的多个query参数

方法注解:

  • @FormUrlEncoded: 标记以form-encoded数据格式发送
  • @Multipart: 标记请求体是有多个part组成
  • @Streaming: 标记请求为流式传输

其他

更多使用方式,请看Retrofit文档:https://square.github.io/retrofit/