Retrofit+Rxjava+okhttp基本使用
new Retrofit.Builder()
//为retrofit设置OkHttpClient
.client(new OkHttpClient().newBuilder()
.connectTimeout(500, TimeUnit.SECONDS)
.readTimeout(500, TimeUnit.SECONDS)
.build()
)
//传入baseUrl
.baseUrl("")
//gosn解析,在网络请求完毕后解析成实体bean
.addConverterFactory(GsonConverterFactory.create())
//集成Rx
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
//返回一个observable对象,将一次网络请求作为一个事件源
.build()
//这里返回传入的service接口
.create(RxService.class)
//调用接口里的方法,到这里返回一个Observable对象
.get("")
//设置事件源线程
.subscribeOn(Schedulers.io())
//设置处理事件源线程
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Consumer<Bean>() {
@Override
public void accept(Bean bean) throws Exception {
//dosomething
}
});
}
interface RxService {
@GET("path/{index}")
Observable<Bean> get(@Path("index") String index);
Retrofit+okhttp负责网络请求
Rxjava负责异步处理与线程控制
以上代码在调用接口的.get()之前的一系列操作,获取的是一次网络请求事件源
为了便捷可以封装成一个Netutils类来输出Observable网络请求事件源对象
Netutils类为单例类,Creat方法暴露两个参数,一个baseUrl,一个接口,输出Observable对象
可根据业务不同再进行扩展
public class NetUtils {
private static NetUtils mClient;
private OkHttpClient.Builder mBuilder;
private NetUtils() {
initOkHttp();
}
public static NetUtils getInstance() {
if (mClient == null) {
synchronized (NetUtils.class) {
if (mClient == null) {
mClient = new NetUtils();
}
}
}
return mClient;
}
public <T> T create(Class<T> service, String baseUrl) {
checkNotNull(service, "service is null");
checkNotNull(baseUrl, "baseUrl is null");
return new Retrofit.Builder()
.baseUrl(baseUrl) //baseurl路径
.client(mBuilder.build()) //okhttpClient
.addConverterFactory(GsonConverterFactory.create()) //Gson
.addCallAdapterFactory(RxJava2CallAdapterFactory.create()) //Rx
.build() //返回一个网络请求事件源
.create(service); //返回service接口,动态代理模式
}
private <T> T checkNotNull(T object, String message) {
if (object == null) {
throw new NullPointerException(message);
}
return object;
}
private void initOkHttp() {
mBuilder = new OkHttpClient.Builder()
.connectTimeout(5, TimeUnit.SECONDS)
.readTimeout(5, TimeUnit.SECONDS);
}
}
使用时:
NetUtils .getInstance()
.create(RxService.class, BaseUrl)
.get("")//接口定义的方法
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Consumer<NewsDataBean>() {
@Override
public void accept(NewsDataBean newsDataBean) throws Exception {
//dosomthing
}
});