您的位置:首页 > 理论基础 > 计算机网络

Retrofit2初尝试(rxjava + okhttp3)

2016-05-25 13:14 543 查看
Retrofit2是一个网络加载相关的工具库,和okhttp是同一个开发者,对于我们的开发还是十分有利的,这次就尝试写一个Retrofit2结合rxjava okhttp3的小demo:网络数据用的是聚合数据的票房排行

github:RetrofitDemo

相关参考资料:怪盗kidou-Retrofit2完全教程

核心代码:

/**
* 电影票房接口
* Created by Jing on 2016/5/24.
*/
public interface BoxOfficeApi {
@GET("boxoffice/rank")
Observable<ServiceResult<List<BoxOffice>>> getBoxOfficeData(@Query("key") String key, @Query("area") String area);
}


接口中写入具体地址,参数

返回参数为RxJava的Observable,当然Retrofit2还有很多可返回参数,如okhttp的Call,详细可以参照资料中的解释。

为了使用retrofit,我们创建一个全局的管理类方便使用。

public class RetrofitManage {
public static RetrofitManage retrofitManage;
private Retrofit retrofit;

public RetrofitManage(){
//OKHTTP拦截器,用于配置
HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient client = new OkHttpClient.Builder()
.addInterceptor(loggingInterceptor) //日志,可以配置 level 为 BASIC / HEADERS / BODY
.retryOnConnectionFailure(true)
.connectTimeout(15, TimeUnit.SECONDS)
.addNetworkInterceptor(loggingInterceptor)
.build();

retrofit = new Retrofit.Builder()
.baseUrl(Constant.BASE_IP)
.client(client)
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.addConverterFactory(GsonConverterFactory.create())
.build();
}

public static RetrofitManage getInstance(){
if(retrofitManage == null){
synchronized (RetrofitManage.class){
if(retrofitManage == null){
retrofitManage = new RetrofitManage();
}
}
}
return retrofitManage;
}

/**
* 获取retrofit对象
* @return
*/
public Retrofit getRetrofit() {
return retrofit;
}

}


okhttp3的自带日志效果还是不错的,比较直观
其中转换器使用的是Gson的GsonConverterFactory

其他选择还有

Jackson: com.squareup.retrofit2:converter-jackson
Moshi: com.squareup.retrofit2:converter-moshi
Protobuf: com.squareup.retrofit2:converter-protobuf
Wire: com.squareup.retrofit2:converter-wire
Simple XML: com.squareup.retrofit2:converter-simplexml
Scalars (primitives, boxed, and String): com.squareup.retrofit2:converter-scalars


然后获取api:

public static BoxOfficeApi boxOfficeApi;

public static BoxOfficeApi getBoxOfficeApi(){
if(boxOfficeApi == null){
boxOfficeApi = RetrofitManage.getInstance().getRetrofit().create(BoxOfficeApi.class);
}
return boxOfficeApi;
}


在activity中(rxjava):

BoxOfficeConnection.getBoxOfficeApi()
.getBoxOfficeData(Constant.JUHE_KEY, "CN") //请求参数
.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Subscriber<ServiceResult<List<BoxOffice>>>() {
@Override
public void onCompleted() {

}

@Override
public void onError(Throwable throwable) {
if (throwable instanceof HttpException) {
HttpException error = (HttpException) throwable;
} else if(throwable instanceof JsonSyntaxException){
Log.w("log", "Json转换错误");
}
throwable.printStackTrace();
}

@Override
public void onNext(ServiceResult<List<BoxOffice>> data) {
adapter.mList = data.getResult();
rcv.setAdapter(adapter);
}
});


这边要注意的是错误异常处理,可以有3种情况:

1.Observable<User>,直接使用body。对于响应码为2XX的,在OnNext方法中直接返回反序列化的body。而非2XX相应码在onError方法中表现为 HttpException ,网络错误在OnError方法中表现为IOException。

2.Observable<Response<User>>,使用 Response 包裹body。所有Http请求的响应体都可以在OnNext方法中拿到,不管响应码是否为2XX。而网络错误会在OnError方法中表现为IOException。

3.Observable<Result<User>>,使用 Result 包裹body。所有Http请求的响应体和网络错误都会在OnNext方法中。

我这边是选择了第一种,具体的处理要根据情况处理。

最基本的网络请求使用介绍就介绍到这里,深入可以看 Retrofit2 完全解析 探索与okhttp之间的关系
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息