一 依赖添加
compile 'com.icefordog:rehttputils:+' //或者 1.0.2 +为最新版本 不定时更新
二 说明
此封装不改写任何底层使用框架 仅作为简单易用的网络请求封装使用(因封装会损失部分扩展性 故不能百分之百适用于所有项目情况 特此说明)
为方便使用故改为aar减少gradle依赖添加
(此库添加依赖如下)
compile 'com.squareup.retrofit2:retrofit:2.3.0' compile 'com.squareup.retrofit2:converter-gson:2.3.0' compile 'com.squareup.retrofit2:adapter-rxjava:2.3.0' compile 'io.reactivex.rxjava2:rxjava:2.1.0' compile 'io.reactivex.rxjava2:rxandroid:2.0.1' compile 'com.squareup.retrofit2:converter-scalars:2.0.0'//添加返回String的支持 compile 'com.trello:rxlifecycle:1.0'//添加-----rxlifecycle的管理 compile 'com.trello:rxlifecycle-components:1.0'
三 使用
添加主机地址
ReHttpUtils.initRetro("https://www.baidu.com");
以请求百度首地址为例 做测试 函数 httpRequest()为异步回调 httpRequestMain()为同步回调 HttpApi为Retrofit中的server接口定义 用法一致 (可自定义于其他名)。
此处以测试类运行 故用同步回调测试说明
1. ReHttpUtils.instans().httpRequestMain(new MysubCribe<String, HttpApi>() {
@Override
public void onCompleted() {
System.out.println("onCompleted==========");
}
@Override
public void onError(Throwable e) {
System.out.println("Throwable=========="+e);
}
@Override
public void onNext(String s) {
System.out.println("s=========="+s);
}
@Override
public Observable<String> getObservable(HttpApi retrofit) {
return retrofit.getBaidu();
}
});
HttpApi-----全部
public interface HttpApi { @GET("/") // 因为我们是解析首页,也就是根目录,所以这边写"/" Observable<String> getBaidu(); }
2.若是要省略 service(也就是httpApi)则 需如下设置
public abstract class TestSubCribe<T> extends MysubCribe<T, HttpApi> { public Class getTempalteType() { return HttpApi.class; } }
请求方式则变成为
ReHttpUtils.instans().httpRequestMain(new TestSubCribe<String>() {
@Override
public void onCompleted() {
}
@Override
public void onError(Throwable e) {
}
@Override
public void onNext(String s) {
}
@Override
public Observable<String> getObservable(HttpApi retrofit) {
return retrofit.getBaidu();
}
});
当然如需要其他特殊回调可自行编写TestSubCribe类 诸如入参 以及post以及其他求情方式这里不做说明请自行百度 retrofit的service的写法
3.下载
DownloadUtils.download("url", new File("xxx"), new DownloadProgressListener() { @Override public void update(long read, long count, boolean done) { } });
直接调此函数 注 此处暂只根据文件名做了断点下载(所以若下载不用文件而使用 同一文件名 暂时未作删除重下处理 故此说明 请自行做好文件管理 以防出现下载时的问题) 此处为异步下载函数 若需要同步下载 则使用downloadOnthis()其他无异。
4.至于Interceptor 的添加此处不做说明 如需要请自行自定义编写规则()
之前上传略有错误---现更改版本使用为1.0.2