Retrofit使用教程(一)

Square公司开源了许多优秀的库,Retrofit就是其中之一。

Retrofit是用来简化APP访问服务器API,如果你的服务器使用的使RESTAPI,那么赶紧使用Retrofit吧。

官方的文档是用GitHub的API说明使用过程的,有的童鞋可能从没用过GitHub的API(比如我),为了简单易懂,这里我使用一个查询手机归属地的API来说明Retrofit的使用过程。

集成

目前我使用的是AndroidStudio,那么在model的build.gradle文件中添加以下引用:

1
2
3
4
compile 'com.squareup.okhttp3:okhttp:3.2.0'
compile 'com.squareup.retrofit2:retrofit:2.0.0-beta4'
compile 'com.google.code.gson:gson:2.6.2'
compile 'com.jakewharton:butterknife:7.0.1'

说明:

  • Retrofit依赖于okhttp,所以需要集成okhttp
  • API返回的数据为JSON格式,在此我使用的是Gson对返回数据解析.请使用最新版的Gson
  • butterknife是用来View绑定的,可以不用写那些烦人的findViewById

返回的数据格式

使用的是百度的API Store提供的API,地址在此:手机号码归属地__API服务_API服务_API Store.

该接口的API主机地址为:http://apis.baidu.com,资源地址为:/apistore/mobilenumber/mobilenumber
需要一个key等于apikey的Header和一个key等于phone的查询关键字,而且该请求为GET请求.

所以我们需要构造一个GET请求,添加一个Header,添加一个Query关键字,访问该API返回的数据格式如下:

1
2
3
4
5
6
7
8
9
10
11
12
{
"errNum": 0,
"retMsg": "success",
"retData": {
"phone": "15210011578",
"prefix": "1521001",
"supplier": "移动",
"province": "北京",
"city": "北京",
"suit": "152卡"
}
}

根据返回结果我们创建数据对象PhoneResult,如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
public class PhoneResult {
/**
* errNum : 0
* retMsg : success
* retData : {"phone":"15210011578","prefix":"1521001","supplier":"移动","province":"北京","city":"北京","suit":"152卡"}
*/
private int errNum;
private String retMsg;
/**
* phone : 15210011578
* prefix : 1521001
* supplier : 移动
* province : 北京
* city : 北京
* suit : 152卡
*/
private RetDataEntity retData;

public void setErrNum(int errNum) {
this.errNum = errNum;
}

public void setRetMsg(String retMsg) {
this.retMsg = retMsg;
}

public void setRetData(RetDataEntity retData) {
this.retData = retData;
}

public int getErrNum() {
return errNum;
}

public String getRetMsg() {
return retMsg;
}

public RetDataEntity getRetData() {
return retData;
}

public static class RetDataEntity {
private String phone;
private String prefix;
private String supplier;
private String province;
private String city;
private String suit;

public void setPhone(String phone) {
this.phone = phone;
}

public void setPrefix(String prefix) {
this.prefix = prefix;
}

public void setSupplier(String supplier) {
this.supplier = supplier;
}

public void setProvince(String province) {
this.province = province;
}

public void setCity(String city) {
this.city = city;
}

public void setSuit(String suit) {
this.suit = suit;
}

public String getPhone() {
return phone;
}

public String getPrefix() {
return prefix;
}

public String getSupplier() {
return supplier;
}

public String getProvince() {
return province;
}

public String getCity() {
return city;
}

public String getSuit() {
return suit;
}
}
}

注:AndroidStudio有个插件 GsonFormat可以很方便地将Json数据转为Java对象.

实现过程

构建

首先,按照官方的说明,我们需要创建一个接口,返回Call<PhoneResult>

官方范例:

1
2
3
4
public interface GitHubService {
@GET("users/{user}/repos")
Call<List<Repo>> listRepos(@Path("user") String user);
}

 

这里我们创建一个名为PhoneService的接口,返回值为Call<PhoneResult>,如下:

1
2
3
4
public interface PhoneService {
@GET("")
Call<PhoneResult> getResult();
}

首先我们需要填写API的相对地址:/apistore/mobilenumber/mobilenumber

1
2
3
4
public interface PhoneService {
@GET("/apistore/mobilenumber/mobilenumber")
Call<PhoneResult> getResult(@Header("apikey") String apikey, @Query("phone") String phone);
}

接着我们要添加一个Header和一个Query关键字,在这里我们需要使用Retrofit提供的注解:

  • @Header用来添加Header
  • @Query用来添加查询关键字

那么,我们的接口就如下了:

1
2
3
4
public interface PhoneService {
@GET("/apistore/mobilenumber/mobilenumber")
Call<PhoneResult> getResult(@Header("apikey") String apikey, @Query("phone") String phone);
}

使用

构建好接口以后,可以使用了!

使用分为四步:

  1. 创建Retrofit对象
  2. 创建访问API的请求
  3. 发送请求
  4. 处理结果

代码如下所示:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
private static final String BASE_URL = "http://apis.baidu.com";
private static final String API_KEY = "8e13586b86e4b7f3758ba3bd6c9c9135";

private void query(){
//1.创建Retrofit对象
Retrofit retrofit = new Retrofit.Builder()
.addConverterFactory(GsonConverterFactory.create())//解析方法
.baseUrl(BASE_URL)//主机地址
.build();

//2.创建访问API的请求
PhoneService service = retrofit.create(PhoneService.class);
Call<PhoneResult> call = service.getResult(API_KEY, phoneView.getText().toString());

//3.发送请求
call.enqueue(new Callback<PhoneResult>() {
@Override
public void onResponse(Call<PhoneResult> call, Response<PhoneResult> response) {
//4.处理结果
if (response.isSuccess()){
PhoneResult result = response.body();
if (result != null){
PhoneResult.RetDataEntity entity = result.getRetData();
}
}
}

@Override
public void onFailure(Call<PhoneResult> call, Throwable t) {

}
});
}

可能会有疑问:第一步中的解析方法GsonConverterFactory.create()是个啥?

官方文档也说明了,这是用来转换服务器数据到对象使用的.该Demo中使用API返回的数据是JSON格式,故此使用Gson来转换,如果服务器返回的是其他类型的数据,则根据需要编写对应的解析方法.

验证

好了,现在可以验证一下了!

编译APP,安装到手机,界面如下:

APP界面

输入手机号码,然后点击查询按钮,结果如下:

结果界面

项目代码详见此处:Dev-Wiki/RetrofitDemo

posted @ 2017-04-26 14:03  天涯海角路  阅读(239)  评论(0)    收藏  举报