Square公司开源了许多优秀的库,Retrofit就是其中之一。html
Retrofit
是用来简化APP访问服务器API,若是你的服务器使用的使RESTAPI,那么赶忙使用Retrofit
吧。java
官方的文档是用GitHub的API说明使用过程的,有的童鞋可能从没用过GitHub的API(好比我),为了简单易懂,这里我使用一个查询手机归属地的API来讲明Retrofit
的使用过程。android
目前我使用的是AndroidStudio
,那么在model的build.gradle文件中添加如下引用:git
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'
说明:github
Retrofit
依赖于okhttp
,因此须要集成okhttp
json
API返回的数据为JSON
格式,在此我使用的是Gson
对返回数据解析.请使用最新版的Gson
api
butterknife
是用来View
绑定的,能够不用写那些烦人的findViewById
了服务器
使用的是百度的API Store提供的API,地址在此:手机号码归属地__API服务_API服务_API Store.ide
该接口的API主机地址为:http://apis.baidu.com
,资源地址为:/apistore/mobilenumber/mobilenumber
须要一个key等于apikey的Header和一个key等于phone的查询关键字,并且该请求为GET请求.gradle
因此咱们须要构造一个GET请求,添加一个Header,添加一个Query关键字,访问该API返回的数据格式以下:
{ "errNum": 0, "retMsg": "success", "retData": { "phone": "15210011578", "prefix": "1521001", "supplier": "移动", "province": "北京", "city": "北京", "suit": "152卡" } }
根据返回结果咱们建立数据对象PhoneResult
,以下:
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>
官方范例:
public interface GitHubService { @GET("users/{user}/repos") Call<List<Repo>> listRepos(@Path("user") String user); }
这里咱们建立一个名为PhoneService
的接口,返回值为Call<PhoneResult>
,以下:
public interface PhoneService { @GET("") Call<PhoneResult> getResult(); }
首先咱们须要填写API的相对地址:/apistore/mobilenumber/mobilenumber
public interface PhoneService { @GET("/apistore/mobilenumber/mobilenumber") Call<PhoneResult> getResult(@Header("apikey") String apikey, @Query("phone") String phone); }
接着咱们要添加一个Header和一个Query关键字,在这里咱们须要使用Retrofit
提供的注解:
@Header
用来添加Header
@Query
用来添加查询关键字
那么,咱们的接口就以下了:
public interface PhoneService { @GET("/apistore/mobilenumber/mobilenumber") Call<PhoneResult> getResult(@Header("apikey") String apikey, @Query("phone") String phone); }
构建好接口之后,可使用了!
使用分为四步:
建立Retrofit对象
建立访问API的请求
发送请求
处理结果
代码以下所示:
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,安装到手机,界面以下:
输入手机号码,而后点击查询按钮,结果以下:
项目代码详见此处:Dev-Wiki/RetrofitDemo
更多文章请访问个人博客:DevWiki Blog