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>

使用

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

使用分为四步:

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

代码如下所示:

[代码]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使用教程的更多相关文章

  1. Android Retrofit使用教程(二)

    上一篇文章讲述了Retrofit的简单使用,这次我们学习一下Retrofit的各种HTTP请求. Retrofit基础 在Retrofit中使用注解的方式来区分请求类型.比如@GET("&q ...

  2. Android Retrofit使用教程(三):Retrofit与RxJava初相逢

    上一篇文章讲述了Retrofit的基本使用,包括GET,POST等请求.今天的文章中Retrofit要与RxJava配合使用. 了解RxJava RxJava有种种好处,我不在这里一一讲述.这里我只给 ...

  3. Android Retrofit 2.0 使用-补充篇

    推荐阅读,猛戳: 1.Android MVP 实例 2.Android Retrofit 2.0使用 3.RxJava 4.RxBus 5.Android MVP+Retrofit+RxJava实践小 ...

  4. Android Studio2.0 教程MAC版 -快捷键篇

    本文转至 Android Studio2.0 教程从入门到精通MAC版 - 提高篇 ( OPEN 开发经验库) 第二篇我们开发了一个Hello World应用,并介绍Android Sutdio的界面 ...

  5. Android图像处理实例教程

    Android图像处理实例教程 原始出处 http://vaero.blog.51cto.com/4350852/856750

  6. android用户界面详尽教程实例

    android用户界面详尽教程实例 1.android用户界面之AlarmManager教程实例汇总http://www.apkbus.com/android-48405-1-1.html2.andr ...

  7. [转]Android Studio系列教程六--Gradle多渠道打包

    转自:http://www.stormzhang.com/devtools/2015/01/15/android-studio-tutorial6/ Android Studio系列教程六--Grad ...

  8. 【Android进阶系列教程】前言

    起因 因为初学Android的时候还没有写博客的意识,现在Android的门是入了,正在进阶的道路上行走,但是就这一路也走了不少的弯路.我想,总得来说Android入门还是比较容易的,网络资源比较丰富 ...

  9. Android Studio使用教程(二)

    以下是本次Google I/O大会发布的IDE Android Studio使用教程第二篇: 在Android Studio使用教程(一)中简要介绍了Android Studio的基本使用,包括安装. ...

随机推荐

  1. 【Combination Sum II 】cpp

    题目: Given a collection of candidate numbers (C) and a target number (T), find all unique combination ...

  2. leetcode 【 Two Sum 】python 实现

    题目: Given an array of integers, find two numbers such that they add up to a specific target number. ...

  3. SEO搜索引擎优化基础

    要如何提高自己网站的知名度,那必须了解一些SEO知识. 1.什么是搜索引擎 所谓的搜索引擎(Search  Engines)是一些能够主动搜索信息(搜索网页上的单词和简短的特定的内容描述)并将其自动索 ...

  4. c语言入门-01

    当我们学c语言我们学些什么. [1]编译机制 当我们写好c的代码,生产了程序,这中间到底做了些什么? 这个就是c语言的编译过程 我们分别来解析这上面的过程. 我们写出我们第一个c程序. #includ ...

  5. 【LeetCode】Merge Sorted Array(合并两个有序数组)

    这道题是LeetCode里的第88道题. 题目描述: 给定两个有序整数数组 nums1 和 nums2,将 nums2 合并到 nums1 中,使得 num1 成为一个有序数组. 说明: 初始化 nu ...

  6. gcc学习记录

    -Wall: 使输出中包含警告信息,提示一些可以避免的错误.如果没有错误,则不会输出信息. -o:后面加上可执行文件的名字.如果不加-o选项,会默认生成a.out可执行文件.举例:gcc -Wall ...

  7. 什么是虚假唤醒 spurious wakeup

    解释一下什么是虚假唤醒? 说具体的例子,比较容易说通. pthread_mutex_t lock; pthread_cond_t notempty; pthread_cond_t notfull; v ...

  8. tomcat源码分析一

    废话少说,拉代码,导入eclipse开干,具体步骤可以参考http://hi.baidu.com/hateeyes/blog/item/7f44942a20ad8f9d023bf66d.html 下面 ...

  9. 【转】ugui自制摇杆

    http://www.cnblogs.com/duyushuang/p/4457691.html 珍爱生命,远离插件. 以上8个字,好好理解. 反正我是这么觉得. 我说的是unity,不是魔兽世界. ...

  10. POJ 2728 Desert King(最优比例生成树 二分 | Dinkelbach迭代法)

    Desert King Time Limit: 3000MS   Memory Limit: 65536K Total Submissions: 25310   Accepted: 7022 Desc ...