易用的 OkHttp 的请求框架,可以结合 RxJava 一起使用。
全部请求通过 OkCall 类去发起。
RequestCall requestCall;
/**
* 普通GET请求
*/
requestCall = OkCall.getInstance().get().url("https://www.baidu.com/").build();
/**
* GET请求,连接放在构造方法内
*/
requestCall = OkCall.getInstance().get("https://www.baidu.com/").build();
/**
* GET请求带参数
*/
Map<String, String> param = new HashMap<>();
requestCall = OkCall.getInstance().get("https://www.baidu.com/").params(param).build();
/**
* GET请求带参数逐个添加
*/
requestCall = OkCall.getInstance().get("https://www.baidu.com/").addParam("key1", "value1").addParam("key2", "value2").build();
/**
* GET请求带请求头
*/
Map<String, String> header = new HashMap<>();
requestCall = OkCall.getInstance().get("https://www.baidu.com/").headers(header).build();
/**
* GET请求带请求头逐个添加
*/
requestCall = OkCall.getInstance().get("https://www.baidu.com/").addHeader("key1", "value1").addHeader("key2", "value2").build();
/**
* GET请求带让参数encoded编码
*/
requestCall = OkCall.getInstance().get("https://www.baidu.com/").encoded(true).build();
/**
* 请求回调返回 Response
*/
requestCall.enqueue(new Callback() {
@Override
public void onResponse(Call call, Response response) {
}
@Override
public void onFailure(Call call, Throwable t) {
}
});
/**
* 请求回调返回 String
*/
requestCall.enqueue(new StringCallBack() {
@Override
public void onResponse(String result) {
}
@Override
public void onFailure(String errorString) {
}
});
/**
* 请求回调返回 自己想要解析的类型
*/
requestCall.enqueue(new BaseDataCallBack<String>() {
@Override
public void onResponse(String result) {
}
@Override
public void onFailure(String errorString) {
}
});
所有请求方法可以如上面例子一样搭配,下面只演示其中一种。
OkCall.getInstance()
.post("https://www.baidu.com/")
.addParam("key1","value1")
.addParam("key2","value2")
.build()
.enqueue(new StringCallBack() {
@Override
public void onResponse(String result) {
}
@Override
public void onFailure(String errorString) {
}
});
OkCall.getInstance()
.postString("https://www.baidu.com/")
.addParam("key1","value1")
.addParam("key2","value2")
.content("your string")
.build()
.enqueue(new StringCallBack() {
@Override
public void onResponse(String result) {
}
@Override
public void onFailure(String errorString) {
}
});
OkCall.getInstance()
.postFile("https://www.baidu.com/")
.file(new File("123"))
.build()
.enqueue(new StringCallBack() {
@Override
public void onResponse(String result) {
}
@Override
public void onFailure(String errorString) {
}
});
OkCall.getInstance()
.postForm("https://www.baidu.com/")
.addFile(new FormFile("1","2",new File("123")))
.build()
.enqueue(new StringCallBack() {
@Override
public void onResponse(String result) {
}
@Override
public void onFailure(String errorString) {
}
});
String url = "https://www.easy-mock.com/mock/5b4c0d81a618510d7322b2f0/example/query";
OkCall.injectCall()
.get(url)
.build()
.enqueue(new BaseDataCallBack<LZX>() {
@Override
public void onResponse(LZX result) {
Log.i("MainActivity", "result = " + result.toString());
}
@Override
public void onFailure(String errorString) {
Log.i("MainActivity", "onFailure = " + errorString);
}
});
public class LZX {
public String name;
public String msg;
@Override
public String toString() {
return "LZX{" +
"name='" + name + '\'' +
", msg='" + msg + '\'' +
'}';
}
}
如果需要结合RxJava使用,调用时只需要把 build 改为 rxBuild 即可。 rxBuild 返回的是一个 Observable 对象,同样地,也提供了 rxFlowable,rxSingle,rxMaybe,rxCompletable方法,返回各自不同的对象。
- RxUtil
RxUtil 是一个封装好线程切换的工具类,使用时结合 compose 方法即可,例子:
OkCall.getInstance()
.postForm("https://www.baidu.com/")
.addFile(new FormFile("1", "2", new File("123")))
.rxBuild()
.compose(RxUtil.<Response>rxSchedulerObservable())
.subscribe(new Consumer<Response>() {
@Override
public void accept(Response response) throws Exception {
}
}, new Consumer<Throwable>() {
@Override
public void accept(Throwable throwable) throws Exception {
}
});
- ResultTransformer
ResultTransformer 是一个数据类型转换类,里面使用了 Gson,只需要传入你想转换的类型,使用时结合 compose 方法即可,例子:
OkCall.getInstance()
.get()
.url("https://www.baidu.com/")
.rxBuild()
.compose(new ResultTransformer<>(String.class))
.compose(RxUtil.<String>rxSchedulerObservable())
.subscribe(new Consumer<String>() {
@Override
public void accept(String json) throws Exception {
}
});
结合 RxJava 只需要把 build 方法换成 rxBuild 方法即可,其他都一样。
- 普通回调
String url = "https://www.easy-mock.com/mock/5b4c0d81a618510d7322b2f0/example/query";
OkCall.injectCall()
.get(url)
.rxBuild()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Consumer<Response>() {
@Override
public void accept(Response response) throws Exception {
Log.i("MainActivity", "json = " + response.body().string());
}
}, new Consumer<Throwable>() {
@Override
public void accept(Throwable throwable) throws Exception {
Log.i("MainActivity", "Throwable = " + throwable.getMessage());
}
});
- 带数据解析
String url = "https://www.easy-mock.com/mock/5b4c0d81a618510d7322b2f0/example/query";
OkCall.injectCall()
.get(url, null)
.rxBuild()
.compose(new ResultTransformer<>(LZX.class))
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Consumer<LZX>() {
@Override
public void accept(LZX json) {
Log.i("MainActivity", "json = " + json.toString());
}
}, new Consumer<Throwable>() {
@Override
public void accept(Throwable throwable) {
Log.i("MainActivity", "throwable = " + throwable.getMessage());
}
});
只需要使用 compose ,new 一个 ResultTransformer 对象传入要解析成的实体类的 class 即可。
rxBuild 返回的是 Observable,如果你想返回 Flowable,则用 rxBuildFlowable 即可,同样的,如果想返回 Single,则用 rxBuildSingle, 想返回 Maybe,则用 rxBuildMaybe
RxJava 下载调用 rxDownload 方法,参数有三个,下载url,文件保存路径,保存文件名。回调信息为 DownloadInfo , 字段如下:
public class DownloadInfo {
public static final String SUCCESS = "success"; //成功
public static final String FAIL = "fail"; //失败
public static final String DOWNLOADING = "downloading"; //下载中
private String status; //下载状态:SUCCESS,FAIL,DOWNLOADING
private String destFileDir; //保存路径
private String destFileName; //保存文件名
private File file; //file对象,下载失败的时候为null
private long downloadProgress = 0; //当前下载进度
private long downloadTotalSize = 0; //总大小
...
}
onNext(DownloadInfo info) 回调中会不断回调下载进度直到下载完成为止,所以可以通过 info.getDownloadPercent() 是否等于 1,或者 info.getStatus() 是否等于 DownloadInfo.SUCCESS 来判断是否下载完成。
OkHttpClient 通过 OkHttpClientConfig 进行配置。在 Application 中进行配置并调用 OkCall.initClient 方法即可。
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient okHttpClient = new OkHttpClientConfig.Builder(this)
.setAddInterceptor(interceptor)
.build();
OkCall.initClient(okHttpClient);