Android使用Retrofit+RxJava网络请求小结
breewf

注:由于Retrofit2.0相较之前版本改进较大,以下方法使用Retrofit2.0的方法

基本用法

定义接口:

1
2
3
4
public interface GitHubService {
@GET("users/{user}/repos")
Call<List<Repo>> listRepos(@Path("user") String user);
}

使用类 Retrofit 生成接口 GitHubService 的实现:

1
2
3
4
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://api.github.com/")
.build();
GitHubService service = retrofit.create(GitHubService.class);

之后就可以直接调用生成的GitHubServcie实例去发送请求:

1
Call<List<Repo>> repos = service.listRepos("octocat");

注意:baseUrl和注解中url连接的”/“最好写在baseUrl的后面,而不是注解中url的前面,否则可能会出现不可预知的错误。

请求的URL可以在函数中使用替换块和参数进行动态更新,替换块是{ }包围的字符串,相应的参数必须使用相同的字符串被@Path进行注释

1
2
@GET("group/{id}/users")
List<User> groupList(@Path("id") int groupId);

也可以添加查询参数

1
2
@GET("group/{id}/users")
List<User> groupList(@Path("id") int groupId, @Query("sort") String sort);

复杂的查询参数可以使用Map进行组合

1
2
@GET("group/{id}/users")
List<User> groupList(@Path("id") int groupId, @QueryMap Map<String, String> options);

实例介绍

首先添加依赖:

1
compile 'com.squareup.retrofit2:retrofit:2.0.0-beta4'

定义接口

要进行网络请求,首先要有请求的接口,这里以一个请求天气的接口为例,Retrofit使用以下方法定义一个接口:

1
2
3
4
5
6
7
/**
* http://wthrcdn.etouch.cn/weather_mini?citykey=101010100
*/
public interface ApiWeatherService {
@GET("weather_mini")
Observable<WeatherBean> getWeatherInfo(@Query("citykey") String cityKey);
}

注意:上面使用Observable(被观察者、事件源)返回而不是Call的原因是请求结束后要配合使用RxJava。

网络请求

使用Retrofit进行网络请求:

1
2
3
4
5
6
7
8
9
Retrofit retrofit = new Retrofit.Builder()
//baseUrl
.baseUrl("http://wthrcdn.etouch.cn/")
//如果你想接收json结果并解析,你必须把Gson Converter作为一个独立的依赖添加进来
.addConverterFactory(GsonConverterFactory.create())
//Retrofit团队有已经准备好了的CallAdapter module。其中最著名的module可能是为RxJava准备的CallAdapter,它将作为Observable返回
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.build();
ApiWeatherService weatherService = retrofit.create(ApiWeatherService.class);

注意:要使用GSON解析和CallAdapter(配合RxJava使用),你的项目需要添加以下依赖:

1
2
compile 'com.squareup.retrofit2:converter-gson:2.0.0-beta4'
compile 'com.squareup.retrofit2:adapter-rxjava:2.0.0-beta4'

在Retrofit 2.0中,你需要自己插入一个Converter(addConverterFactory),不然的话Retrofit只能接收字符串结果。同样,Retrofit 2.0也不再依赖于Gson。
你可以使用Gson、Jackson或者其它的Converter modules,一般我们使用Gson。

使用RxJava

你可以完全像RxJava那样使用它,如果你想让subscribe部分的代码在主线程中被调用,需要把observeOn(AndroidSchedulers.mainThread())添加到链表中。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
Observable<WeatherBean> observable = weatherService.getWeatherInfo("101010100");
observable.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Subscriber<WeatherBean>() {
@Override
public void onCompleted() {
Log.i("RxJava----", "onCompleted");
}

@Override
public void onError(Throwable e) {
Log.e("RxJava----", "onError" + e.toString());
}

@Override
public void onNext(WeatherBean weatherBean) {
rxJavaTv.setText("天气信息:" + weatherBean.getData().getGanmao());
}
});

注意:要使用RxJava和AndroidSchedulers.mainThread(),你需要添加依赖:

1
2
compile 'io.reactivex:rxjava:1.1.0'
compile 'io.reactivex:rxandroid:1.1.0'

至此,一个使用Retrofit和RxJava进行简单的网络请求并解析的例子就完成了。简单两段代码实现了网络请求、解析、异步,结构也非常的清晰,不得不说Retrofit和RxJava的强大,也值得我们深入学习。
听说Retrofit和RxJava更配哦!

参考文章:
Retrofit 2.0:有史以来最大的改进
Retrofit2.0使用详解