最近看了很多关于Retrofit和Rxjava的文档介绍。终于在弄清Rxjava后顺利的弄懂了Retrofit。
网上有很多人都介绍了它们的联合使用,但是我看过之后理解不是太好。可能我太笨。
不过,今天写这篇博客的目的就是想来说说它们之间如何使用以及使用的时候遇到的坑。
这两者的关系并不大,但是联合在一起使用是非常简便的。Rxjava的响应式编程加上Retrofit的注解式请求用起来是非常爽的。
并且Retrofit内置的是Okhttp,所以这更加的让Retrofit变得强大。
如果在看这篇博客的时候你对java注解、Rxjava还有Okhttp还不够了解,建议先去了解这两个东西。
给出友情链接:
RxJava——响应式和区域化的优秀框架(java&android)
相信看到这里,你已经对上面三个知识有了了解。
那么接下来切入正题。
先来加入依赖库:
compile 'io.reactivex:rxjava:1.0.14'
compile 'io.reactivex:rxandroid:1.0.1'
compile 'com.squareup.retrofit:adapter-rxjava:2.0.0-beta2'
compile 'com.squareup.retrofit:retrofit:2.0.0-beta2'
compile 'com.squareup.retrofit:converter-gson:2.0.0-beta2'
没错,你需要的库就是这么多。若要联合它们三者使用,就必须这么多。
我来按顺序介绍。
1,Rxjava库
2,RxAndroid库
3,Retrofit适配Rxjava的库
4,Retrofit库
5,Retrofit适配Gson的库(添加了这个库后不用再添加Gson库,因为已经内置)
另外还要有Okhttp依赖库。在android sdk中已经内置。似乎Retrofit中也内置了Okhttp,所以我项目中没有加入okhttp依赖库,但是okhttp依旧可以使用。
这里需要说明一下,第五个依赖库根据你的项目需求来添加。
一般的项目来说都是使用json数据的。若你的项目是使用xml或者其他的数据格式,那么对应的添加。
(以下版本号需要与retrofit版本号保持一致,并且以retrofit官网给出的版本号为准。)
1)Gson: compile 'com.squareup.retrofit2:converter-gson:2.0.1'
2)Jackson: compile 'com.squareup.retrofit2:converter-jackson:2.0.1'
3)Moshi: compile 'com.squareup.retrofit2:converter-moshi:2.0.1'
4)Protobuf: compile 'com.squareup.retrofit2:converter-protobuf:2.0.1'
5)Wire: compile 'com.squareup.retrofit2:converter-wire:2.0.1'
6)Simple XML: compile 'com.squareup.retrofit2:converter-simplexml:2.0.1' 7)Scalars (primitives, boxed, and String): compile 'com.squareup.retrofit2:converter-scalars:2.0.1'
好了。依赖库加完以后。我们就开始请求了。
我们先来个测试url
private String ip = "http://gc.ditu.aliyun.com/geocoding?a=上海市&aa=松江区&aaa=车墩镇";
这个是阿里云根据地区名获取经纬度接口。
返回json数据
{
"lon":120.58531,
"level":2,
"address":"",
"cityName":"",
"alevel":4,
"lat":31.29888
}
我们先来写好实体类AliAddrsBean和IndexRequestBean
public class AliAddrsBean {
private double lon;
private int level;
private String address;
private String cityName;
private int alevel;
private double lat;
//get/set方法忽略
}
public class IndexRequestBean {
private String a;//一级城市
private String aa;//二级城市
private String aaa;//三级城市
//get/set方法忽略
}
Retrofit的请求管理类RetrofitManage(先写成单例)
private RetrofitManage() {
}
public static RetrofitManage getInstance() {
return RetrofitManager.retrofitManage;
}
private static class RetrofitManager {
private static final RetrofitManage retrofitManage = new RetrofitManage();
}