Retrofit的使用
参照文档:http://gank.io/post/56e80c2c677659311bed9841
一、创建Retrofit
mRetrofit = new Retrofit.Builder() .baseUrl(URL_PATH)//设置URL地址 .addConverterFactory(GsonConverterFactory.create())//设置使用Gson解析 .addCallAdapterFactory(RxJavaCallAdapterFactory.create())//设置使用RXJAVA的形式,如果不设置则为OkHttp的模式 .build();//创建Retrofit
二、设置接收使用的javaBean(成员变量名为json的键,如果是jsonArray则需要使用List<>封装)
public class HttpResult<T> { private int count; private int start; private int total; private String title; //用来模仿Data private T subjects; public int getCount() { return count; } public void setCount(int count) { this.count = count; } public int getStart() { return start; } public void setStart(int start) { this.start = start; } public int getTotal() { return total; } public void setTotal(int total) { this.total = total; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public T getSubjects() { return subjects; } public void setSubjects(T subjects) { this.subjects = subjects; } @Override public String toString() { StringBuffer sb = new StringBuffer(); sb.append("title=" + title + " count=" + count + " start=" + start); if (null != subjects) { sb.append(" subjects:" + subjects.toString()); } return sb.toString(); } }
三、设置传输接口
public interface DouBanApi { @GET("top250")//变量地址 Observable<HttpResult<List<Subject>>> getMovies(@Query("start")int start,@Query("count")int count); }//Query表示需要上传的参数名
四、设置回调接口
DouBanApi douBanApi = mRetrofit.create(DouBanApi.class); Observable<HttpResult<List<Subject>>> observable = douBanApi.getMovies(start,count); observable.subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Subscriber<HttpResult<List<Subject>>>() { @Override public void onCompleted() { } @Override public void onError(Throwable e) { } @Override public void onNext(HttpResult<List<Subject>> listHttpResult) { } }); }