在上一篇中说到OkHttp,接下来要介绍一个最近火的不要不要的框架retrofit,这是一个类型安全的REST客户端请求库,把REST API返回的数据转化为Java对象,retrofit的网路调用是基于RxJava的
先来说一下retrofit的用法
1.创建实例
Retrofit retrofit = new Retrofit.Bulider()
.baseUrl("http://apis.haoservice.com/"); //必须以“/”结束,否则异常
.build();
2.接口定义
public interface LifeService {
@GET("lifeservice/exp")
Call getDatas(@Query("key") String key,@Query("com") String com,@Query("no") String no,@Query("order") String order);
}
@GET表示以GET方式请求,请求地址是baseURL+GET地址,即http://apis.haoservice.com/lifeservice/exp
定义一个方法getDatas(),@query请求参数,以key=value呈现,所以最后呈现的请求是http://apis.haoservice.com/lifeservice/exp/key=key&com=com&no=no
3.用retrofit创建Service的代理对象
LifeService lifeService = retrofit.create(LifeService.class);
这样就可以调用getDatas()方法了
4.接口调用
lifeService.getDatas(key, "shunfeng", "1901541511780", "desc").enqueue(new Callback() {
@Override
public void onResponse(Call call, Response response) {
if (response.body() != null) {
Life lifedata = response.body();
Life.ResultEntity datas = lifedata.getResult();
Log.i("onResponse", "数据:" + datas);
} else {
Log.e("onResponse: body==null","no");
}
}
@Override
public void onFailure(Call call, Throwable t) {
Log.e("onResponse: body==null","nono");
}
);
注解:
1.HTTP注解 @HTTP(method = "get",path = "lifeservice/exp/",hasBody = false)
这是指明请求方式是GET 方式,method中大小写不区分,路径是path后面的路径,加载baseurl后面,hasBody是是否有请求体
2.Query、Field、Part都支持数组和Iterable
FieldMap和QueryMap接受类型是 Map
3.@query()请求参数以key=value形式拼接到baseurl后面
再来说说RxJava
RxJava是异步的观察者模式的响应式扩展的Java实现
RxJava中有几个概念,Observable是被观察者,Observer是观察者,subscribe是订阅,observer和observable通过subscribe联系起来,当observable有变化时,通过订阅关心可以告知observer,感觉类似onclickListener,他们的订阅关系是observable.subscribe(observer);看起来很怪,但是是为了下面的逻辑更加的简单理解,注意这订阅顺序。订阅有三个方法,分别是onNext();onCompleted();onError();在onNext()中完成想要实现的功能,在onCompleted()是完结,onError是异常处理 。
来看看RxJava的用法
1.创建observer
Observer observer = new Observer(){
onNext(){
//功能实现
}
onCompleted(){
}
onError(){
}
}
2.创建observable
Observable observable = Observable.create(new Observable.OnSubscribe(){
public call(Subcriber subscriber){
subscriber.onNext();
subscriber.onComplent();
subscriber.onError();
}
});
Observable observable = Observable.just("A","B","C"); //将传入参数依次发送
Observable observable = Observable.from(Iterable); //将传入的数组或者Iterable拆分成具体对象依次发送
3.subscribe订阅
observable.Subscribe(observer)
Rxjava还可以特别简单的切换线程
observable.subscribeOn(Schedulers.newThread()); //切换到新的线程
observable.observeOn(Schedulers.mainThread()); //切换回主线程
retrofit+rxjava注意点:
compile 'com.squareup.retrofit2:adapter-rxjava:2.0.0-beta4'
compile 'com.squareup.retrofit2:retrofit:2.0.0-beta4'
compile 'com.squareup.retrofit2:converter-gson:2.0.0-beta4'
添加依赖时,这三个要注意是一致的,版本号要相同
compile 'com.google.code.gson:gson:2.2.4'
compile 'com.squareup.okhttp:okhttp:2.0.0'
还有就是添加这两个,okhttp和gson的依赖,我就是少添加一个gson依赖,导致cannot resolve symbol GsonConverterFactory
最后上来一个例子,看看RxJava+Retrofit的具体应用,大致先了解一下
1.定义接口LifeService
public interface LifeService {
@GET("lifeservice/exp")
Call getDatas(@Query("key") String key,@Query("com") String com,@Query("no") String no,@Query("order") String order);
@GET("lifeservice/exp")
rx.Observable getRxData(@Query("key") String key,@Query("com") String com,@Query("no") String no,@Query("order") String order);
}
第一个方法是只用Retrofit的,第二个方法是retrofit+rxjava的
注意有的时候Observable
2.定义Life.class把要用到的要处理的请求的数据在这Set和Get到
3.在Activity中执行
public class MainActivity extends AppCompatActivity {
String baseUrl = "http://apis.haoservice.com/";
String key = "0fae2997422441a1ae30bf8b858b0c39";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getdelivery();
getRxDelivery();
}
private void getdelivery(){
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(baseUrl)
.addConverterFactory(GsonConverterFactory.create()
.build();
LifeService lifeService = retrofit.create(LifeService.class);
lifeService.getDatas(key, "shunfeng", "1901541511780", "desc").enqueue(new Callback() {
@Override
public void onResponse(Call call, Response response) {
if (response.body() != null) {
Life lifedata = response.body();
Life.ResultEntity datas = lifedata.getResult();
Log.i("onResponse", "数据:" + datas);
} else {
Log.e("onResponse: body==null","no");
}
}
@Override
public void onFailure(Call call, Throwable t) {
Log.e("onResponse: body==null","nono");
}
});
}
private void getRxDelivery(){
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(baseUrl)
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.build();
LifeService lifeService = retrofit.create(LifeService.class);
rx.Observable observable = lifeService.getRxData(key,"shunfeng","1901541511789","desc");
observable.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
.subscribe(new Subscriber() {
@Override
public void onCompleted() {
Toast.makeText(getApplicationContext(), "Completed", Toast.LENGTH_SHORT).show();
}
@Override
public void onError(Throwable e) {
Toast.makeText(getApplicationContext(), "Error", Toast.LENGTH_SHORT).show();
}
@Override
public void onNext(Life life) {
Life.ResultEntity resultEntity = life.getResult();
Toast.makeText(getApplicationContext(), "success"+resultEntity, Toast.LENGTH_SHORT).show();
}
});
}
}