Android Retrofit使用教程
Square公司开源了许多优秀的库,Retrofit就是其中之一。
Retrofit是用来简化APP访问服务器API,如果你的服务器使用的使RESTAPI,那么赶紧使用Retrofit吧。
官方的文档是用GitHub的API说明使用过程的,有的童鞋可能从没用过GitHub的API(比如我),为了简单易懂,这里我使用一个查询手机归属地的API来说明Retrofit的使用过程。
集成
目前我使用的是AndroidStudio,那么在model的build.gradle文件中添加以下引用:
[代码]xml代码:
|
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返回的数据格式如下:
{
"errNum": 0,
"retMsg": "success",
"retData": {
"phone": "15210011578",
"prefix": "1521001",
"supplier": "移动",
"province": "北京",
"city": "北京",
"suit": "152卡"
}
}
根据返回结果我们创建数据对象PhoneResult,如下:
[代码]java代码:
|
01
02
03
04
05
06
07
08
09
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>
官方范例:
[代码]java代码:
|
1
2
3
4
|
public interface GitHubService { @GET("users/{user}/repos") Call<list<repo>> listRepos(@Path("user") String user);}</list<repo> |
这里我们创建一个名为PhoneService的接口,返回值为Call<PhoneResult>,如下:
[代码]java代码:
|
1
2
3
4
|
public interface PhoneService { @GET("") Call<phoneresult> getResult();}</phoneresult> |
首先我们需要填写API的相对地址:/apistore/mobilenumber/mobilenumber
[代码]java代码:
|
1
2
3
4
|
public interface PhoneService { @GET("/apistore/mobilenumber/mobilenumber") Call<phoneresult> getResult(@Header("apikey") String apikey, @Query("phone") String phone);}</phoneresult> |
接着我们要添加一个Header和一个Query关键字,在这里我们需要使用Retrofit提供的注解:
@Header用来添加Header@Query用来添加查询关键字
那么,我们的接口就如下了:
[代码]java代码:
|
1
2
3
4
|
public interface PhoneService { @GET("/apistore/mobilenumber/mobilenumber") Call<phoneresult> getResult(@Header("apikey") String apikey, @Query("phone") String phone);}</phoneresult> |
使用
构建好接口以后,可以使用了!
使用分为四步:
- 创建Retrofit对象
- 创建访问API的请求
- 发送请求
- 处理结果
代码如下所示:
[代码]java代码:
|
01
02
03
04
05
06
07
08
09
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) { } });}</phoneresult></phoneresult></phoneresult></phoneresult></phoneresult> |
可能会有疑问:第一步中的解析方法GsonConverterFactory.create()是个啥?
官方文档也说明了,这是用来转换服务器数据到对象使用的.该Demo中使用API返回的数据是JSON格式,故此使用Gson来转换,如果服务器返回的是其他类型的数据,则根据需要编写对应的解析方法.
验证
好了,现在可以验证一下了!
编译APP,安装到手机,界面如下:

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

项目代码详见此处:Dev-Wiki/RetrofitDemo
Android Retrofit使用教程的更多相关文章
- Android Retrofit使用教程(二)
上一篇文章讲述了Retrofit的简单使用,这次我们学习一下Retrofit的各种HTTP请求. Retrofit基础 在Retrofit中使用注解的方式来区分请求类型.比如@GET("&q ...
- Android Retrofit使用教程(三):Retrofit与RxJava初相逢
上一篇文章讲述了Retrofit的基本使用,包括GET,POST等请求.今天的文章中Retrofit要与RxJava配合使用. 了解RxJava RxJava有种种好处,我不在这里一一讲述.这里我只给 ...
- Android Retrofit 2.0 使用-补充篇
推荐阅读,猛戳: 1.Android MVP 实例 2.Android Retrofit 2.0使用 3.RxJava 4.RxBus 5.Android MVP+Retrofit+RxJava实践小 ...
- Android Studio2.0 教程MAC版 -快捷键篇
本文转至 Android Studio2.0 教程从入门到精通MAC版 - 提高篇 ( OPEN 开发经验库) 第二篇我们开发了一个Hello World应用,并介绍Android Sutdio的界面 ...
- Android图像处理实例教程
Android图像处理实例教程 原始出处 http://vaero.blog.51cto.com/4350852/856750
- android用户界面详尽教程实例
android用户界面详尽教程实例 1.android用户界面之AlarmManager教程实例汇总http://www.apkbus.com/android-48405-1-1.html2.andr ...
- [转]Android Studio系列教程六--Gradle多渠道打包
转自:http://www.stormzhang.com/devtools/2015/01/15/android-studio-tutorial6/ Android Studio系列教程六--Grad ...
- 【Android进阶系列教程】前言
起因 因为初学Android的时候还没有写博客的意识,现在Android的门是入了,正在进阶的道路上行走,但是就这一路也走了不少的弯路.我想,总得来说Android入门还是比较容易的,网络资源比较丰富 ...
- Android Studio使用教程(二)
以下是本次Google I/O大会发布的IDE Android Studio使用教程第二篇: 在Android Studio使用教程(一)中简要介绍了Android Studio的基本使用,包括安装. ...
随机推荐
- loj2045 「CQOI2016」密钥破解
CQOI 板子大赛之 pollard rho #include <iostream> #include <cstdio> using namespace std; typede ...
- android基础知识杂记
Activity中获取视图组件对象:public View findViewById(@IdRes int id) 该方法以组件的资源ID为参数,返回一个视图对象View,需要强转成具体的视图类对象. ...
- Android坐标getLeft,getRight,getTop,getBottom,getLocationInWindow和getLocationOnScreen
Android中获取坐标点的一些方法解释 一.getLocationInWindow和getLocationOnScreen的区别 // location [0]--->x坐标,location ...
- 什么是事务?MySQL如何支持事务?
什么是事务? 事务是由一步或几步数据库操作序列组成逻辑执行单元,这系列操作要么全部执行,要么全部放弃执行.程序和事务是两个不同的概念.一般而言:一段程序中可能包含多个事务.(说白了就是几步的数据库操作 ...
- c语言入门-01
当我们学c语言我们学些什么. [1]编译机制 当我们写好c的代码,生产了程序,这中间到底做了些什么? 这个就是c语言的编译过程 我们分别来解析这上面的过程. 我们写出我们第一个c程序. #includ ...
- mvcs项目搭建
项目结构 下载链接:http://pan.baidu.com/s/1hsGtShA
- List里面的对象被覆盖
对于for循环,当对象创建在for循环外时,list里面的内容会被覆盖··· 解决办法:把对象创建放入for循环里面: 具体原理:若是放到在for外,对象是同一个,放到for到里面,每次都创建一个新的 ...
- linux系统——etc下的passwd 文件
etcpasswd 文件 在登陆时要求输入用户名和密码,就是根据这个来的. root::0:0:root:/root:/bin/bash bin:x:1:1:bin:/dev/null:/bin/fa ...
- 调试Java代码(Eclipse)汇总
Java 10个调试技巧(基础❤❤❤❤❤) Eclipse断点调试(和上一篇基本类似,补充❤❤) 使用Eclipse开发和调试java程序(从安装eclipse开始,特别细,有设置条件断点,回退的具体 ...
- Databus架构分析与初步实践
简介 Databus是一个低延迟.可靠的.支持事务的.保持一致性的数据变更抓取系统.由LinkedIn于2013年开源.Databus通过挖掘数据库日志的方式,将数据库变更实时.可靠的从数据库拉取出来 ...