接口请求规范
2021-08-16 本文已影响0人
ChasenZhang
1、创建ApiServer
public interface ApiServer {
//须自己实现getInstance()方法
static ApiServer getInstance(){
return HttpCreator.getServer(ApiServer.class);
}
@POST("common/encrypt")
Observable<User> requestEncrptTest(@Body Map request);
@POST("common/unencrypt")
Observable<String> requestUnencrptTest(@Body Map request);
}
注:每一个Server接口都需要写一个静态方法getInstance(),返回的是对应接口的一个Retrofit封装的实例,方便调用。接口内部方法的返回值必须是Observable<T>。请求参数如果是写在请求体内的,则以map封装。
2、在Presnenter里调用
public class DemoPresenter extends BasePresenter implements DemoContract.IDemoPresenter {
@Override
public void doDemo(String param) {
Map<String,String> request = new HashMap<>();
request.put("password","123456");
request.put("nickname","chenpeng");
ApiServer.getInstance()
.requestEncrptTest(request)
.compose(RxJavaUtils.compose(getLifecycleTransformer()))
.subscribe(new ApiCallBack<User>() {
@Override
public void onSuccess(User user) {
}
@Override
public void onApiFail(ApiException exception) {
}
@Override
public void onFail(Throwable e) {
}
@Override
public void onComplete() {
}
});
}
}
注:
注意在ApiServer请求的时候中间调用了方法compose(RxJavaUtils.compose(getLifecycleTransformer())),其在内部处理了线程的切换和生命周期(在Activity或Fragment销毁时会自动取消本次请求),
getLifecycleTransformer()是BasePresenter里的方法。
ApiCallBack是项目封装的一个网络回调接口,代码如下
public abstract class ApiCallBack<T> extends ResourceObserver<T> {
@Override
public void onNext(T t) {
onSuccess(t);
}
@Override
public void onError(Throwable e) {
if(e instanceof ApiException){
onApiFail((ApiException)e);
}else {
e.printStackTrace();
onFail(e);
}
}
abstract public void onSuccess(T t);
abstract public void onApiFail(ApiException exception);
abstract public void onFail(Throwable e);
}
ApiException是对服务器的响应封装的一个异常,代码如下
public class ApiException extends RuntimeException {
private String code;
private String message;
public static ApiException build(String code,String message){
ApiException exception = new ApiException();
exception.code = code;
exception.message = message;
return exception;
}
public String getCode() {
return code;
}
@Nullable
@Override
public String getMessage() {
return message;
}
}
RxJavaUtils代码如下
public class RxJavaUtils {
public static <T> ObservableTransformer<T, T> compose(final LifecycleTransformer<T> lifecycleTransformer) {
return new ObservableTransformer<T, T>() {
@Override
public ObservableSource<T> apply(Observable<T> upstream) {
return upstream.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.compose(lifecycleTransformer);
}
};
}
}