用过Retrofit的小伙伴都知道,当Retrofit和RxJava结合使用的时候,我们需要在定义Api的接口中的请求方法的返回值设置成一个带有解析实体类泛型的Observable
下面Rxjava和Okhttp结合使用
导入依赖:
compile 'io.reactivex.rxjava2:rxjava:2.0.1'
compile 'io.reactivex.rxjava2:rxandroid:2.0.1'
compile 'com.squareup.okhttp3:okhttp:3.4.1'
下面是网络工具类,关键位置有注释
public class NetTool {
private static OkHttpClient okHttpClient;
private static NetTool instance;
private NetTool() {
okHttpClient = new OkHttpClient();
}
//单例双重锁线程安全
public static NetTool getInstance() {
if (instance == null) {
synchronized (NetTool.class) {
if (instance == null) {
instance = new NetTool();
}
}
}
return instance;
}
//get请求 声明泛型 括号里传入网址和实体类
public <T> Observable<T> request(final String url, final Class<T> clazz) {
return Observable.create(new ObservableOnSubscribe<String>() {
@Override
public void subscribe(ObservableEmitter<String> e) throws Exception {
e.onNext(url);
}
}).map(new Function<String, String>() {
@Override
public String apply(String s) throws Exception {
//参数里的s是onNext方法传递过来的url
Request request = new Request.Builder().url(s).build();
Response respose = okHttpClient.newCall(request).execute();
//然后请求成功后响应的String数据继续对其map转换
//在下个map转换中进行Json解析
return respose.body().string();
}
}).map(new Function<String, T>() {
@Override
public T apply(String s) throws Exception {
Gson gson = new Gson();
T t = gson.fromJson(s,clazz);
return t;
}
});
}
//post 提交键值对
public <T> Observable<T> postKeyValue (final String baseurl, final Map<String,String> map, final Class<T> clazz) {
return Observable.create(new ObservableOnSubscribe<String>() {
@Override
public void subscribe(ObservableEmitter<String> e) throws Exception {
e.onNext(baseurl);
}
}).map(new Function<String, String>() {
@Override
public String apply(String s) throws Exception {
//参数里的s是onNext方法传递过来的baseurl
FormBody.Builder builder = new FormBody.Builder();
//遍历map 添加多个参数进入请求体
Set<String> keyset = map.keySet();
Iterator<String> keyIterator = keyset.iterator();
while (keyIterator.hasNext()){
String key = keyIterator.next();
builder.add(key,map.get(key));
}
//生成请求体
RequestBody requestBody= builder.build();
Request request = new Request.Builder().url(s).post(requestBody).build();
Response response = okHttpClient.newCall(request).execute();
return response.body().string();
}
}).map(new Function<String, T>() {
@Override
public T apply(String s) throws Exception {
Gson gson = new Gson();
T t = gson.fromJson(s,clazz);
return t;
}
});
}
//post携带json数据请求
public <T> Observable<T> postJsonstr (final String baseUrl , final Class<T> clazz, final String json){
return Observable.create(new ObservableOnSubscribe<String>() {
@Override
public void subscribe(ObservableEmitter<String> e) throws Exception {
e.onNext(baseUrl);
}
}).map(new Function<String, String>() {
@Override
public String apply(String s) throws Exception {
MediaType JSON = MediaType.parse("application/json; charset=utf-8");
RequestBody body = RequestBody.create(JSON, json);
Request request = new Request.Builder()
.url(baseUrl)
.post(body)
.build();
Response response = okHttpClient.newCall(request).execute();
return response.body().string();
}
}).map(new Function<String, T>() {
@Override
public T apply(String s) throws Exception {
Gson gson = new Gson();
T t = gson.fromJson(s,clazz);
return t;
}
});
}
}
下面是调用代码
//get请求应用
NetTool.getInstance()
.request("http://gank.io/api/data/%E7%A6%8F%E5%88%A9/50/1", PictureBean.class)
.subscribeOn(Schedulers.io())//指定之前被观察者的动作在io线程中操作
.observeOn(AndroidSchedulers.mainThread())//将被观察者返回的数据切换到主线程中
.subscribe(new Consumer<PictureBean>() {
@Override
public void accept(PictureBean pictureBean) throws Exception {
//请求成功,并在子线程完成了解析,返回了实体类
}
}, new Consumer<Throwable>() {
@Override
public void accept(Throwable throwable) throws Exception {
//异常
}
});
//post键值对请求
Map<String,String> postMap = new HashMap<>();
postMap.put("username","louyulin");
postMap.put("password","123456");
NetTool.getInstance()
.postKeyValue("http://...",postMap,PictureBean.ResultsBean.class)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Consumer<PictureBean.ResultsBean>() {
@Override
public void accept(PictureBean.ResultsBean resultsBean) throws Exception {
}
}, new Consumer<Throwable>() {
@Override
public void accept(Throwable throwable) throws Exception {
}
});