Android 初识Retrofit

转载自:http://blog.csdn.net/jdsjlzx/article/details/52015347

什么是 Retrofit ?

Retrofit 是一套 RESTful 架构的 AndroidJava) 客户端实现,基于注解,提供 JSON to POJO(Plain Ordinary Java Object ,简单 Java 对象),POJO to JSON,网络请求(POST,GET, PUT,DELETE 等)封装。

配置环境

在build.gradle中添加

.....

//编译RxJava
compile 'io.reactivex:rxjava:1.1.6'

//编译RxAndroid
compile 'io.reactivex:rxandroid:1.2.1'

//编译Retrofit及其相关库,包括Gson
compile 'com.squareup.okhttp3:okhttp:3.3.1'
compile 'com.squareup.retrofit2:retrofit:2.1.0'
compile 'com.squareup.retrofit2:converter-gson:2.1.0'
compile 'com.squareup.retrofit2:adapter-rxjava:2.1.0'
compile 'com.squareup.okhttp3:logging-interceptor:3.3.1'

 
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15

说明:

Retrofit默认依赖于okhttp,所以需要集成okhttp。 
API返回的数据为JSON格式,在此我使用的是Gson对返回数据解析.请使用最新版的Gson 。

接口

这里我们调试借助百度名人名言API

该接口的API主机地址为:http://apistore.baidu.com; 
需要访问的接口:avatardata/mingrenmingyan/lookup;

需要一个key等于apikey的Header和一个keyword等于名人名言的查询关键字,而且该请求为GET请求.

接口返回json格式:

{
    "total": 10,
    "result": [
        {
            "famous_name": "佚名",
            "famous_saying": "婚姻是一家私人专门银行,存储真爱和默契,提取幸福和快乐。夫妻双方互为账户,且存折是活期的,可以随存随取,而家庭则是这家银行里的柜台,通过它,夫妻双方可以把自己的喜怒哀乐尽情地存进对方的银行里,并可随时提取微笑、鼓励、安慰、体贴、温柔等利息。"
        },
        {
            "famous_name": "英国",
            "famous_saying": "真爱无坦途"
        },
        {
            "famous_name": "狄太人",
            "famous_saying": "一个人真爱的时候,甚至会想不到自己是爱着对方。"
        },
        {
            "famous_name": "佚名",
            "famous_saying": "所有的阻碍,全是对真爱的淬炼。"
        },
        {
            "famous_name": "罗兰",
            "famous_saying": "当你真爱一个人的时候,你是会忘记自己的苦乐得失,而只是关心对方的苦乐得失的。"
        },
        {
            "famous_name": "罗兰",
            "famous_saying": "当两人之间有真爱情的时候,是不会考虑到年龄的问题,经济的条件,相貌的美丑,个子的高矮,等等外在的无关紧要的因素的。假如你们之间存在着这种问题,那你要先问问自己,是否真正在爱才好。"
        },
        {
            "famous_name": "佚名",
            "famous_saying": "真正的勇气是来自内心的真爱。"
        },
        {
            "famous_name": "佚名",
            "famous_saying": "天国般的幸福,存在于对真爱的希望。"
        },
        {
            "famous_name": "狄太人",
            "famous_saying": "一个人真爱的时候,甚至会想不到自己是爱着对方"
        },
        {
            "famous_name": "Shakespeare",
            "famous_saying": "通向真爱的路从无坦途。"
        }
    ],
    "error_code": 0,
    "reason": "Succes"
}
 
 
  • 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
  • 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
定义实体类

我们根据上面API返回的json数据来创建一个Famous数据对象,我们可以利用AndroidStudio插件 GsonFormat 快速方便的将json数据转为Java 对象。

Famous.java

public class Famous {

    //下面变量的定义要与接口中的字段名字保持一致
    public int total;
    public int error_code;
    public String reason;
    public List<FamousInfo> result;


    public static class FamousInfo {
        public String famous_name;
        public String famous_saying;
    }

}
 
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15

注意:如果你的字段有跟json不一样的,要在字段上面加注解@SerializedName,@SerializedName是指定Json格式中的Key名。

如上面的错误码字段,你就像定义为code,而服务器返回的是error_code,这个时候就应该这么写:

@SerializedName("error_code") 
 public int code;
 
 
  • 1
  • 2
  • 1
  • 2

使用

首先定义

public abstract class BaseApi {
    public static final String API_SERVER = "服务器地址"
    private static final OkHttpClient mOkHttpClient = new OkHttpClient();
    private static Retrofit mRetrofit;

    protected static Retrofit getRetrofit() {
            if (Retrofit == null) {
                Context context = Application.getInstance().getApplicationContext();
                //设定30秒超时
                mOkHttpClient.setConnectTimeout(30, TimeUnit.SECONDS);
                //设置拦截器,以用于自定义Cookies的设置
                mOkHttpClient.networkInterceptors()
                            .add(new CookiesInterceptor(context));
                //设置缓存目录
                File cacheDirectory = new File(context.getCacheDir()
                                        .getAbsolutePath(), "HttpCache");
                Cache cache = new Cache(cacheDirectory, 20 * 1024 * 1024);
                mOkHttpClient.setCache(cache);
                //构建Retrofit
                mRetrofit = new Retrofit.Builder()
                        //配置服务器路径
                        .baseUrl(API_SERVER + "/")  
                        //设置日期解析格式,这样可以直接解析Date类型
                        .setDateFormat("yyyy-MM-dd HH:mm:ss")  
                        //配置转化库,默认是Gson
                     .addConverterFactory(GsonConverterFactory.create())
                        //配置回调库,采用RxJava
                        .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                        //设置OKHttpClient为网络客户端
                        .client(mOkHttpClient)
                        .build();
            }
            return mRetrofit;
        }
}
 
 
  • 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
  • 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

定义FamousApi

public class FamousApi extends BaseApi{
    //定义接口
    private interface FamousService {
    @GET("/avatardata/mingrenmingyan/lookup")  
    Observable<Famous> getFamousList(@Header("apiKey") String apiKey,  
                                     @Query("keyword") String keyword,  
                                     @Query("page") int page,  
                                     @Query("rows") int rows);  
    }
    protected static final FamousService service = getRetrofit().create(FamousService.class);


    public static Observable<UserProfileResp> getFamousList(String apiKey,String keyword, int page, int rows){
        return service.getFamousList(apiKey, keyword, page, rows);
    }


}
 
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18

最终使用:

public void getFamousList(){
    FamousApi.getFamousList("apiKey","人才",1,20)
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(new Subscriber<Famous>(){
                        @Override
                        public void onCompleted() {                 
                        }                       
                        @Override
                        public void onError(Throwable e) {                  
                        }                       
                        @Override
                        public void onNext(Famous famous) {
                             List<FamousInfo> list = famous.result;
                             //填充UI          
                        }
        });
}

 
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19

如下效果:

图片名称

参考demo:https://github.com/jdsjlzx/RetrofitDemo

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值