Demo1 : 获取豆瓣电影TOP250
只用Retrofit的写法
API :
接口类(start: 起始值 count: 要获取的个数)
public interface IMovieService {
@GET("v2/movie/top250")
Call<MovieEntity> getMovie(@Query("start") int start, @Query("count") int count);
}
请求代码
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://api.douban.com/")
.addConverterFactory(GsonConverterFactory.create())
.build();
IMovieService iMovieService = retrofit.create(IMovieService.class);
Call<MovieEntity> movie = iMovieService.getMovie(0, 10);
movie.enqueue(new Callback<MovieEntity>() {
@Override
public void onResponse(Call<MovieEntity> call, Response<MovieEntity> response) {
// Log.e(TAG, "onResponse: " + response.body());
List<MovieEntity.SubjectsBean> subjects = response.body().getSubjects();
for (MovieEntity.SubjectsBean subject : subjects) {
Log.e(TAG, "onResponse: " + subject.getTitle());
}
}
@Override
public void onFailure(Call<MovieEntity> call, Throwable t) {
}
});
PS : 这里只是将获得的每个电影标题打印出来
添加rxjava支持
接口(返回值变为了Observable)
public interface IMovieService {
@GET("v2/movie/top250")
Observable<MovieEntity> getMovie(@Query("start") int start, @Query("count") int count);
}
请求代码
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://api.douban.com/")
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.build();
IMovieService iMovieService = retrofit.create(IMovieService.class);
iMovieService.getMovie(0,10)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.flatMap(new Func1<MovieEntity, Observable<MovieEntity.SubjectsBean>>() {
@Override
public Observable<MovieEntity.SubjectsBean> call(MovieEntity movieEntity) {
return Observable.from(movieEntity.getSubjects());
}
})
.subscribe(new Action1<MovieEntity.SubjectsBean>() {
@Override
public void call(MovieEntity.SubjectsBean subjectsBean) {
Log.e(TAG, "call: " + subjectsBean.getTitle());
}
});