https://github.com/getActivity/EasyHttp/blob/master/HelpDoc.md
public class RequestServer implements IRequestServer {
@NonNull
@Override
public String getHost() {
return "https://www.baidu.com/";
}
@NonNull
@Override
public BodyType getBodyType() {
// 参数以 Json 格式提交(默认是表单)
return BodyType.JSON;
}
}
OkHttpClient okHttpClient = new OkHttpClient.Builder()
.build();
EasyConfig.with(okHttpClient)
// 是否打印日志
.setLogEnabled(BuildConfig.DEBUG)
// 设置服务器配置(必须设置)
.setServer(server)
// 设置请求处理策略(必须设置)
.setHandler(new RequestHandler())
// 设置请求重试次数
.setRetryCount(3)
// 添加全局请求参数
//.addParam("token", "6666666")
// 添加全局请求头
//.addHeader("time", "20191030")
// 启用配置
.into();
EasyConfig.getInstance()
.addParam("token", data.getData().getToken());
# OkHttp3
-keepattributes Signature
-keepattributes *Annotation*
-keep class okhttp3.** { *; }
-keep interface okhttp3.** { *; }
-dontwarn okhttp3.**
-dontwarn okio.**
# 不混淆这个包下的类
-keep class com.xxx.xxx.xxx.xxx.** {
;
}
public final class LoginApi implements IRequestApi {
@NonNull
@Override
public String getApi() {
return "user/login";
}
/** 用户名 */
private String userName;
/** 登录密码 */
private String password;
public LoginApi setUserName(String userName) {
this.userName = userName;
return this;
}
public LoginApi setPassword(String password) {
this.password = password;
return this;
}
}
public final class XxxApi implements IRequestServer, IRequestApi {
@NonNull
@Override
public String getHost() {
return "https://www.baidu.com/";
}
@NonNull
@Override
public String getApi() {
return "user/getInfo";
}
}
EasyHttp.post(this)
.api(new LoginApi()
.setUserName("Android 轮子哥")
.setPassword("123456"))
.request(new HttpCallbackProxy>(activity) {
@Override
public void onHttpSuccess(HttpData data) {
toast("登录成功");
}
});
public final class UpdateImageApi implements IRequestApi, IRequestType {
@NonNull
@Override
public String getApi() {
return "upload/";
}
@NonNull
@Override
public BodyType getBodyType() {
// 上传文件需要使用表单的形式提交
return BodyType.FORM;
}
/** 本地图片 */
private File image;
public UpdateImageApi(File image) {
this.image = image;
}
public UpdateImageApi setImage(File image) {
this.image = image;
return this;
}
}
EasyHttp.post(this)
.api(new UpdateImageApi(file))
.request(new OnUpdateListener() {
@Override
public void onUpdateStart(Call call) {
mProgressBar.setVisibility(View.VISIBLE);
}
@Override
public void onUpdateProgressChange(int progress) {
mProgressBar.setProgress(progress);
}
@Override
public void onUpdateSuccess(Void result) {
toast("上传成功");
}
@Override
public void onUpdateFail(Exception e) {
toast("上传失败");
}
@Override
public void onUpdateEnd(Call call) {
mProgressBar.setVisibility(View.GONE);
}
});
EasyHttp.download(this)
.method(HttpMethod.GET)
.file(new File(Environment.getExternalStorageDirectory(), "微信.apk"))
//.url("https://qd.myapp.com/myapp/qqteam/AndroidQQ/mobileqq_android.apk")
.url("http://dldir1.qq.com/weixin/android/weixin708android1540.apk")
.md5("2E8BDD7686474A7BC4A51ADC3667CABF")
.listener(new OnDownloadListener() {
@Override
public void onDownloadStart(File file) {
mProgressBar.setVisibility(View.VISIBLE);
}
@Override
public void onDownloadProgressChange(File file, int progress) {
mProgressBar.setProgress(progress);
}
@Override
public void onDownloadSuccess(File file) {
toast("下载完成:" + file.getPath());
installApk(XxxActivity.this, file);
}
@Override
public void onDownloadFail(File file, Exception e) {
toast("下载出错:" + e.getMessage());
}
@Override
public void onDownloadEnd(File file) {
mProgressBar.setVisibility(View.GONE);
}
}).start();
File outputFile;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
ContentValues values = new ContentValues();
.........
// 生成一个新的 uri 路径
Uri outputUri = getContentResolver().insert(MediaStore.Xxx.Media.EXTERNAL_CONTENT_URI, values);
// 适配 Android 10 分区存储特性
outputFile = new FileContentResolver(context, outputUri);
} else {
outputFile = new File(xxxx);
}
EasyHttp.post(this)
.api(new XxxApi()
.setImage(outputFile))
.request(new HttpCallbackProxy>(this) {
@Override
public void onHttpSuccess(Xxx data) {
}
});
PostRequest postRequest = EasyHttp.post(MainActivity.this);
try {
HttpData data = postRequest
.api(new SearchBlogsApi()
.setKeyword("搬砖不再有"))
.execute(new ResponseClass>() {});
toast("请求成功,请看日志");
} catch (Exception e) {
toast(e.getMessage());
}
public final class RequestHandler implements IRequestHandler {
private final Application mApplication;
private final MMKV mMmkv;
public RequestHandler(Application application) {
mApplication = application;
mMmkv = MMKV.mmkvWithID("http_cache_id");
}
..................
@Nullable
@Override
public Object readCache(@NonNull HttpRequest> httpRequest, @NonNull Type type, long cacheTime) {
String cacheKey = HttpCacheManager.generateCacheKey(httpRequest);
String cacheValue = HttpCacheManager.getMmkv().getString(cacheKey, null);
if (cacheValue == null || "".equals(cacheValue) || "{}".equals(cacheValue)) {
return null;
}
EasyLog.printLog(httpRequest, "----- readCache cacheKey -----");
EasyLog.printJson(httpRequest, cacheKey);
EasyLog.printLog(httpRequest, "----- readCache cacheValue -----");
EasyLog.printJson(httpRequest, cacheValue);
return GsonFactory.getSingletonGson().fromJson(cacheValue, type);
}
@Override
public boolean writeCache(@NonNull HttpRequest> httpRequest, @NonNull Response response, @NonNull Object result) {
String cacheKey = HttpCacheManager.generateCacheKey(httpRequest);
String cacheValue = GsonFactory.getSingletonGson().toJson(result);
if (cacheValue == null || "".equals(cacheValue) || "{}".equals(cacheValue)) {
return false;
}
EasyLog.printLog(httpRequest, "----- writeCache cacheKey -----");
EasyLog.printJson(httpRequest, cacheKey);
EasyLog.printLog(httpRequest, "----- writeCache cacheValue -----");
EasyLog.printJson(httpRequest, cacheValue);
return HttpCacheManager.getMmkv().putString(cacheKey, cacheValue).commit();
}
@Override
public void clearCache() {
HttpCacheManager.getMmkv().clearMemoryCache();
HttpCacheManager.getMmkv().clearAll();
}
}
public class HttpCacheManager {
private volatile static MMKV sMmkv;
/**
* 获取单例的 MMKV 实例
*/
public static MMKV getMmkv() {
if(sMmkv == null) {
synchronized (RequestHandler.class) {
if (sMmkv == null) {
sMmkv = MMKV.mmkvWithID("http_cache_id");
}
}
}
return sMmkv;
}
/**
* 生成缓存的 key
*/
public static String generateCacheKey(@NonNull HttpRequest> httpRequest) {
IRequestApi requestApi = httpRequest.getRequestApi();
return "用户 id" + "\n" + requestApi.getApi() + "\n" + GsonFactory.getSingletonGson().toJson(requestApi);
}
}
public enum CacheMode {
/**
* 默认(按照 Http 协议来缓存)
*/
DEFAULT,
/**
* 不使用缓存(禁用 Http 协议缓存)
*/
NO_CACHE,
/**
* 只使用缓存
*
* 已有缓存的情况下:读取缓存 -> 回调成功
* 没有缓存的情况下:请求网络 -> 写入缓存 -> 回调成功
*/
USE_CACHE_ONLY,
/**
* 优先使用缓存
*
* 已有缓存的情况下:先读缓存 —> 回调成功 —> 请求网络 —> 刷新缓存
* 没有缓存的情况下:请求网络 -> 写入缓存 -> 回调成功
*/
USE_CACHE_FIRST,
/**
* 只在网络请求失败才去读缓存
*/
USE_CACHE_AFTER_FAILURE
}
public final class XxxApi implements IRequestApi, IRequestCache {
@NonNull
@Override
public String getApi() {
return "xxx/";
}
@NonNull
@Override
public CacheMode getCacheMode() {
// 设置优先使用缓存
return CacheMode.USE_CACHE_FIRST;
}
}
public class XxxServer implements IRequestServer {
@NonNull
@Override
public String getHost() {
return "https://www.xxxxxxx.com/";
}
@NonNull
@Override
public CacheMode getCacheMode() {
// 只在请求失败才去读缓存
return CacheMode.USE_CACHE_AFTER_FAILURE;
}
}
lifecycleScope.launch(Dispatchers.IO) {
try {
val bean = EasyHttp.post(this@XxxActivity)
.api(XxxApi().apply {
setXxx(xxx)
setXxxx(xxxx)
})
.execute(object : ResponseClass>() {})
withContext(Dispatchers.Main) {
// 在这里进行 UI 刷新
}
} catch (e: Exception) {
toast(e.message)
}
}
OkHttpClient okHttpClient = new OkHttpClient.Builder()
.cookieJar(new XxxCookieJar())
.build();
EasyConfig.with(okHttpClient)
.setXxx()
.into();
EasyConfig.getInstance().addParam("key", "value");
EasyConfig.getInstance().removeParam("key");
EasyConfig.getInstance().addHeader("key", "value");
EasyConfig.getInstance().removeHeader("key");
EasyConfig.getInstance().setInterceptor(new IRequestInterceptor() {
@Override
public void interceptArguments(@NonNull HttpRequest> httpRequest, @NonNull HttpParams params, @NonNull HttpHeaders headers) {
headers.put("key", "value");
params.put("key", "value");
}
});
public final class XxxApi implements IRequestApi {
@NonNull
@Override
public String getApi() {
return "xxx/xxxx";
}
@HttpIgnore
private String token;
}
public class XxxServer implements IRequestServer {
@NonNull
@Override
public String getHost() {
return "https://www.xxxxxxx.com/";
}
}
EasyConfig.getInstance().setServer(new XxxServer());
public final class XxxApi extends XxxServer implements IRequestApi {
@NonNull
@Override
public String getApi() {
return "xxx/xxxx";
}
}
public final class XxxApi implements IRequestServer, IRequestApi {
@NonNull
@Override
public String getHost() {
return "https://www.xxxxxxx.com/";
}
@NonNull
@Override
public String getApi() {
return "xxx/xxxx";
}
}
public class TestServer implements IRequestServer {
@NonNull
@Override
public String getHost() {
return "https://www.test.xxxxxxx.com/";
}
}
public class ReleaseServer implements IRequestServer {
@NonNull
@Override
public String getHost() {
return "https://www.xxxxxxx.com/";
}
}
IRequestServer server;
if (BuildConfig.DEBUG) {
server = new TestServer();
} else {
server = new ReleaseServer();
}
EasyConfig.getInstance().setServer(server);
public class H5Server implements IRequestServer {
@NonNull
@Override
public String getHost() {
IRequestServer server = EasyConfig.getInstance().getServer();
if (server instanceof TestServer) {
return "https://www.test.h5.xxxxxxx.com/";
}
return "https://www.h5.xxxxxxx.com/";
}
}
public final class UserAgreementApi extends H5Server implements IRequestApi {
@NonNull
@Override
public String getApi() {
return "user/agreement";
}
}
public class XxxServer implements IRequestServer {
@NonNull
@Override
public String getHost() {
return "https://www.xxxxxxx.com/";
}
@NonNull
@Override
public BodyType getBodyType() {
return BodyType.FORM;
}
public class XxxServer implements IRequestServer {
@NonNull
@Override
public String getHost() {
return "https://www.xxxxxxx.com/";
}
@NonNull
@Override
public BodyType getBodyType() {
return BodyType.JSON;
}
public final class XxxApi implements IRequestApi, IRequestType {
@NonNull
@Override
public String getApi() {
return "xxx/xxxx";
}
@NonNull
@Override
public BodyType getBodyType() {
return BodyType.JSON;
}
}
场景 |
表单方式 |
Json 方式 |
多级参数 |
不支持 |
支持 |
文件上传 |
支持 |
不支持 |
public interface IRequestInterceptor {
/**
* 拦截参数
*
* @param httpRequest 接口对象
* @param params 请求参数
* @param headers 请求头参数
*/
default void interceptArguments(@NonNull HttpRequest> httpRequest, @NonNull HttpParams params, @NonNull HttpHeaders headers) {}
/**
* 拦截请求头
*
* @param httpRequest 接口对象
* @param request 请求头对象
* @return 返回新的请求头
*/
@NonNull
default Request interceptRequest(@NonNull HttpRequest> httpRequest, @NonNull Request request) {
return request;
}
/**
* 拦截器响应头
*
* @param httpRequest 接口对象
* @param response 响应头对象
* @return 返回新的响应头
*/
@NonNull
default Response interceptResponse(@NonNull HttpRequest> httpRequest, @NonNull Response response) {
return response;
}
}
// 在框架初始化的时候设置拦截器
EasyConfig.with(okHttpClient)
// 设置请求参数拦截器
.setInterceptor(new XxxInterceptor())
.into();
public final class XxxApi implements IRequestApi {
@NonNull
@Override
public String getApi() {
return "xxx/xxxx";
}
@HttpIgnore
private String address;
public final class XxxApi implements IRequestApi {
@NonNull
@Override
public String getApi() {
return "xxx/xxxx";
}
@HttpHeader
private String time;
}
public final class XxxApi implements IRequestApi {
@NonNull
@Override
public String getApi() {
return "xxx/xxxx";
}
@HttpRename("k")
private String keyword;
}
public final class XxxApi implements IRequestApi {
@NonNull
@Override
public String getApi() {
return "xxx/xxxx";
}
private File file;
}
public final class XxxApi implements IRequestApi {
@NonNull
@Override
public String getApi() {
return "xxx/xxxx";
}
private InputStream inputStream;
}
public final class XxxApi implements IRequestApi {
@NonNull
@Override
public String getApi() {
return "xxx/xxxx";
}
private RequestBody requestBody;
public final class XxxApi implements IRequestApi {
@NonNull
@Override
public String getApi() {
return "xxx/xxxx";
}
private List files;
}
// 设置请求重试次数
EasyConfig.getInstance().setRetryCount(3);
// 设置请求重试时间
EasyConfig.getInstance().setRetryTime(1000);
OkHttpClient.Builder builder = new OkHttpClient.Builder();
builder.readTimeout(5000, TimeUnit.MILLISECONDS);
builder.writeTimeout(5000, TimeUnit.MILLISECONDS);
builder.connectTimeout(5000, TimeUnit.MILLISECONDS);
EasyConfig.with(builder.build())
.into();
public final class XxxApi implements IRequestApi, IRequestClient {
@NonNull
@Override
public String getApi() {
return "xxxx/";
}
@NonNull
@Override
public OkHttpClient getOkHttpClient() {
OkHttpClient.Builder builder = EasyConfig.getInstance().getOkHttpClient().newBuilder();
builder.readTimeout(5000, TimeUnit.MILLISECONDS);
builder.writeTimeout(5000, TimeUnit.MILLISECONDS);
builder.connectTimeout(5000, TimeUnit.MILLISECONDS);
return builder.build();
}
}
EasyConfig.getInstance().setLogEnabled(false);
EasyConfig.with(okHttpClient)
.......
// 设置自定义的日志打印策略
.setLogStrategy(new XxxStrategy())
.into();
// 取消和这个 LifecycleOwner 关联的请求
EasyHttp.cancel(LifecycleOwner lifecycleOwner);
// 取消指定 Tag 标记的请求
EasyHttp.cancel(Object tag);
// 取消所有请求
EasyHttp.cancel();
EasyHttp.post(MainActivity.this)
.api(new XxxApi())
// 延迟 5 秒后请求
.delay(5000)
.request(new HttpCallbackProxy>(MainActivity.this) {
@Override
public void onHttpSuccess(HttpData result) {
}
});
public final class XxxApi implements IRequestApi {
@NonNull
@Override
public String getApi() {
return "article/query/" + pageNumber + "/json";
}
@HttpIgnore
private int pageNumber;
public XxxApi setPageNumber(int pageNumber) {
this.pageNumber = pageNumber;
return this;
}
}
EasyHttp.post(this)
.api(new RequestUrl("https://xxxx.com/aaaa"))
.request(new HttpCallbackProxy(this) {
@Override
public void onHttpSuccess(Xxx result) {
}
});
HttpSslConfig sslConfig = HttpSslFactory.generateSslConfig();
OkHttpClient okHttpClient = new OkHttpClient.Builder()
.sslSocketFactory(sslConfig.getsSLSocketFactory(), sslConfig.getTrustManager())
.hostnameVerifier(HttpSslFactory.generateUnSafeHostnameVerifier())
.build();
public final class HttpUrls {
/** 获取用户信息 */
public static final String GET_USER_INFO = "user/getUserInfo";
}
EasyHttp.post(this)
.api(HttpUrls.GET_USER_INFO)
.request(new HttpCallbackProxy>(this) {
@Override
public void onHttpSuccess(HttpData result) {
}
});
EasyHttp.post(new ActivityLifecycle(this))
.api(new XxxApi())
.request(new HttpCallbackProxy>(this) {
@Override
public void onHttpSuccess(HttpData result) {
}
});
EasyHttp.post(ApplicationLifecycle.getInstance())
.api(new XxxApi())
.tag("abc")
.request(new OnHttpListener>() {
@Override
public void onHttpSuccess(HttpData result) {
}
@Override
public void onHttpFail(Exception e) {
}
});
public class BaseViewModel extends ViewModel implements LifecycleOwner {
private final LifecycleRegistry mLifecycle = new LifecycleRegistry(this);
public BaseViewModel() {
mLifecycle.handleLifecycleEvent(Lifecycle.Event.ON_CREATE);
mLifecycle.handleLifecycleEvent(Lifecycle.Event.ON_RESUME);
}
@Override
protected void onCleared() {
super.onCleared();
mLifecycle.handleLifecycleEvent(Lifecycle.Event.ON_DESTROY);
}
@NonNull
@Override
public Lifecycle getLifecycle() {
return mLifecycle;
}
}
public class XxxViewModel extends BaseViewModel {
public void xxxx() {
EasyHttp.post(this)
.api(new XxxApi())
.request(new OnHttpListener>() {
@Override
public void onHttpSuccess(HttpData result) {
}
@Override
public void onHttpFail(Exception e) {
}
});
}
}
EasyHttp.post(this)
.api(new XxxApi())
.request(new HttpCallbackProxy(this) {
@Override
public void onHttpStart(Call call) {
// 重写方法并注释父类调用
//super.onHttpStart(call);
}
@Override
public void onHttpEnd(Call call) {
// 重写方法并注释父类调用
//super.onHttpEnd(call);
}
});
EasyHttp.post(this)
.api(new XxxApi())
.request(new OnHttpListener() {
@Override
public void onHttpSuccess(Xxx result) {
}
@Override
public void onHttpFail(Exception e) {
}
});
List parameter = new ArrayList<>();
list.add(xxx);
list.add(xxx);
String json = gson.toJson(parameter);
EasyHttp.post(this)
.api(new XxxApi())
.body(new JsonBody(json))
.request(new HttpCallbackProxy>(this) {
@Override
public void onHttpSuccess(HttpData result) {
}
});
HashMap parameter = new HashMap<>();
// 添加全局参数
HashMap globalParams = EasyConfig.getInstance().getParams();
Set keySet = globalParams.keySet();
for (String key : keySet) {
parameter.put(key, globalParams.get(key));
}
// 添加自定义参数
parameter.put("key1", value1);
parameter.put("key2", value2);
String json = gson.toJson(parameter);
JsonBody jsonBody = new JsonBody(json)
EasyHttp.post(this)
.api(new XxxApi())
.body(jsonBody)
.request(new HttpCallbackProxy>(this) {
@Override
public void onHttpSuccess(HttpData result) {
}
});
EasyHttp.post(this)
.api(new XxxApi())
// 表示回调是在子线程中进行
.schedulers(ThreadSchedulers.IOThread)
.request(new HttpCallbackProxy>(this) {
@Override
public void onHttpSuccess(HttpData result) {
}
});
EasyHttp.post(this)
.api(new XxxApi())
.body(RequestBody body)
.request(new HttpCallbackProxy>(this) {
@Override
public void onHttpSuccess(HttpData result) {
}
});
public final class XxxApi implements IRequestApi {
@NonNull
@Override
public String getApi() {
return "xxx/xxx";
}
@HttpHeader
@HttpRename("Content-Type")
private String contentType = "application/x-www-form-urlencoded;charset=utf-8";
}
public final class CustomParameterApi implements IRequestApi {
@HttpIgnore
@NonNull
private final Map parameters;
public CustomParameterApi() {
this(new HashMap<>());
}
public CustomParameterApi(@NonNull Map parameters) {
this.parameters = parameters;
}
@NonNull
@Override
public String getApi() {
Set keys = parameters.keySet();
StringBuilder builder = new StringBuilder();
int index = 0;
for (String key : keys) {
String value = parameters.get(key);
if (index == 0) {
builder.append("?");
}
builder.append(key)
.append("=")
.append(value);
if (index < keys.size() - 1) {
builder.append("&");
}
index++;
}
return "xxx/xxx" + builder;
}
public CustomParameterApi putParameter(String key, String value) {
parameters.put(key, value);
return this;
}
public CustomParameterApi removeParameter(String key) {
parameters.remove(key);
return this;
}
}
CustomParameterApi api = new CustomParameterApi();
api.putParameter("key1", "value1");
api.putParameter("key2", "value2");
EasyHttp.get(this)
.api(api)
.request(new HttpCallbackProxy(this) {
@Override
public void onHttpSuccess(Xxx result) {
}
});
public final class XxxApi implements IRequestApi {
@NonNull
@Override
public String getApi() {
return "article/query?pageNumber=" + pageNumber;
}
@HttpIgnore
private int pageNumber;
public XxxApi setPageNumber(int pageNumber) {
this.pageNumber = pageNumber;
return this;
}
}
dependencies {
// RxJava:https://github.com/ReactiveX/RxJava
implementation 'io.reactivex.rxjava2:rxandroid:2.1.1'
implementation 'io.reactivex.rxjava2:rxjava:2.2.12'
}
Observable.create(new ObservableOnSubscribe>() {
@Override
public void subscribe(ObservableEmitter> emitter) throws Exception {
HttpData data1;
try {
data1 = EasyHttp.post(MainActivity.this)
.api(new SearchBlogsApi()
.setKeyword("搬砖不再有"))
.execute(new ResponseClass>() {});
} catch (Exception e) {
throw e;
}
HttpData data2;
try {
data2 = EasyHttp.post(MainActivity.this)
.api(new SearchBlogsApi()
.setKeyword(data1.getMessage()))
.execute(new ResponseClass>() {});
} catch (Exception e) {
throw e;
}
emitter.onNext(data2);
emitter.onComplete();
}
})
// 让被观察者执行在IO线程
.subscribeOn(Schedulers.io())
// 让观察者执行在主线程
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Consumer>() {
@Override
public void accept(HttpData data) throws Exception {
Log.i("EasyHttp", "最终结果为:" + data.getMessage());
}
}, new Consumer() {
@Override
public void accept(Throwable throwable) throws Exception {
toast(throwable.getMessage());
}
});
// 发起轮询请求,共发起三次请求,第一次请求在 5 秒后触发,剩下两次在 1 秒 和 2 秒后触发
Observable.intervalRange(1, 3, 5000, 1000, TimeUnit.MILLISECONDS)
// 让被观察者执行在 IO 线程
.subscribeOn(Schedulers.io())
// 让观察者执行在主线程
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Consumer() {
@Override
public void accept(Long aLong) throws Exception {
EasyHttp.post(MainActivity.this)
.api(new SearchBlogsApi()
.setKeyword("搬砖不再有"))
.request(new HttpCallbackProxy>(MainActivity.this) {
@Override
public void onHttpSuccess(HttpData result) {
}
});
}
});
Observable.create(new ObservableOnSubscribe>() {
@Override
public void subscribe(ObservableEmitter> emitter) throws Exception {
EasyHttp.post(MainActivity.this)
.api(new SearchBlogsApi()
.setKeyword("搬砖不再有"))
.request(new HttpCallbackProxy>(MainActivity.this) {
@Override
public void onHttpSuccess(HttpData result) {
emitter.onNext(result);
emitter.onComplete();
}
@Override
public void onHttpFail(Exception e) {
super.onHttpFail(e);
emitter.onError(e);
}
});
}
})
.map(new Function, String>() {
@Override
public String apply(HttpData data) throws Exception {
int curPage = data.getData().getCurPage();
int pageCount = data.getData().getPageCount();
return curPage + "/" + pageCount;
}
})
// 让被观察者执行在 IO 线程
.subscribeOn(Schedulers.io())
// 让观察者执行在主线程
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Consumer() {
@Override
public void accept(String s) throws Exception {
Log.i("EasyHttp", ""当前页码位置" + s);
}
}, new Consumer() {
@Override
public void accept(Throwable throwable) throws Exception {
toast(throwable.getMessage());
}
});