Android MVVM框架搭建(二)OKHttp + Retrofit + RxJava(1),2024Android高级面试题总结

methodName = methodName.substring(0, 1).toUpperCase() + methodName.substring(1);

StringBuilder stringBuilder = new StringBuilder();

stringBuilder.append(“[ (”).append(className).append(“:”).append(lineNumber).append(“)#”).append(methodName).append(" ] ");

if (msg != null && type != JSON) {

stringBuilder.append(msg);

}

String logStr = stringBuilder.toString();

switch (type) {

case V:

Log.v(tag, logStr);

break;

case D:

Log.d(tag, logStr);

break;

case I:

Log.i(tag, logStr);

break;

case W:

Log.w(tag, logStr);

break;

case E:

Log.e(tag, logStr);

break;

case A:

Log.wtf(tag, logStr);

break;

case JSON: {

if (TextUtils.isEmpty(msg)) {

Log.d(tag, “Empty or Null json content”);

return;

}

String message = null;

try {

if (msg.startsWith(“{”)) {

JSONObject jsonObject = new JSONObject(msg);

message = jsonObject.toString(JSON_INDENT);

} else if (msg.startsWith(“[”)) {

JSONArray jsonArray = new JSONArray(msg);

message = jsonArray.toString(JSON_INDENT);

}

} catch (JSONException e) {

e(tag, e.getCause().getMessage() + “\n” + msg);

return;

}

printLine(tag, true);

message = logStr + LINE_SEPARATOR + message;

String[] lines = message.split(LINE_SEPARATOR);

StringBuilder jsonContent = new StringBuilder();

for (String line : lines) {

jsonContent.append("║ ").append(line).append(LINE_SEPARATOR);

}

Log.d(tag, jsonContent.toString());

printLine(tag, false);

}

break;

default:

break;

}

}

private static void printLine(String tag, boolean isTop) {

if (isTop) {

Log.d(tag, “╔═══════════════════════════════════════════════════════════════════════════════════════”);

} else {

Log.d(tag, “╚═══════════════════════════════════════════════════════════════════════════════════════”);

}

}

}

三、构建网络框架


1. Base

在通过网络请求返回数据时,先进行一个数据解析,得到结果码和错误信息,在network包下新建一个BaseResponse类,代码如下:

/**

  • 基础返回类

  • @author llw

*/

public class BaseResponse {

//返回码

@SerializedName(“res_code”)

@Expose

public Integer responseCode;

//返回的错误信息

@SerializedName(“res_error”)

@Expose

public String responseError;

}

然后再自定义一个BaseObserver类,继承自rxjava的Observer。依然在network包下创建,代码如下:

/**

  • 自定义Observer

  • @author llw

*/

public abstract class BaseObserver implements Observer {

//开始

@Override

public void onSubscribe(Disposable disposable) {

}

//继续

@Override

public void onNext(T t) {

onSuccess(t);

}

//异常

@Override

public void onError(Throwable e) {

onFailure(e);

}

//完成

@Override

public void onComplete() {

}

//成功

public abstract void onSuccess(T t);

//失败

public abstract void onFailure(Throwable e);

}

2. 异常处理

在实际的网络请求中有很多的异常信息和错误码,需要对这些信息要处理,在network包下新建一个errorhandler包,包下新建一个HttpErrorHandler类,代码如下:

/**

  • 网络错误处理

  • @author llw

*/

public class HttpErrorHandler implements Function<Throwable, Observable> {

/**

  • 处理以下两类网络错误:

  • 1、http请求相关的错误,例如:404,403,socket timeout等等;

  • 2、应用数据的错误会抛RuntimeException,最后也会走到这个函数来统一处理;

*/

@Override

public Observable apply(Throwable throwable) throws Exception {

//通过这个异常处理,得到用户可以知道的原因

return Observable.error(ExceptionHandle.handleException(throwable));

}

}

然后再在network包下创建一个ExceptionHandle类,代码如下:

/**

  • 异常处理

  • @author llw

*/

public class ExceptionHandle {

//未授权

private static final int UNAUTHORIZED = 401;

//禁止的

private static final int FORBIDDEN = 403;

//未找到

private static final int NOT_FOUND = 404;

//请求超时

private static final int REQUEST_TIMEOUT = 408;

//内部服务器错误

private static final int INTERNAL_SERVER_ERROR = 500;

//错误网关

private static final int BAD_GATEWAY = 502;

//暂停服务

private static final int SERVICE_UNAVAILABLE = 503;

//网关超时

private static final int GATEWAY_TIMEOUT = 504;

/**

  • 处理异常

  • @param throwable

  • @return

*/

public static ResponseThrowable handleException(Throwable throwable) {

//返回时抛出异常

ResponseThrowable responseThrowable;

if (throwable instanceof HttpException) {

HttpException httpException = (HttpException) throwable;

responseThrowable = new ResponseThrowable(throwable, ERROR.HTTP_ERROR);

switch (httpException.code()) {

case UNAUTHORIZED:

responseThrowable.message = “未授权”;

break;

case FORBIDDEN:

responseThrowable.message = “禁止访问”;

break;

case NOT_FOUND:

responseThrowable.message = “未找到”;

break;

case REQUEST_TIMEOUT:

responseThrowable.message = “请求超时”;

break;

case GATEWAY_TIMEOUT:

responseThrowable.message = “网关超时”;

break;

case INTERNAL_SERVER_ERROR:

responseThrowable.message = “内部服务器错误”;

break;

case BAD_GATEWAY:

responseThrowable.message = “错误网关”;

break;

case SERVICE_UNAVAILABLE:

responseThrowable.message = “暂停服务”;

break;

default:

responseThrowable.message = “网络错误”;

break;

}

return responseThrowable;

} else if (throwable instanceof ServerException) {

//服务器异常

ServerException resultException = (ServerException) throwable;

responseThrowable = new ResponseThrowable(resultException, resultException.code);

responseThrowable.message = resultException.message;

return responseThrowable;

} else if (throwable instanceof JsonParseException

|| throwable instanceof JSONException

|| throwable instanceof ParseException) {

responseThrowable = new ResponseThrowable(throwable, ERROR.PARSE_ERROR);

responseThrowable.message = “解析错误”;

return responseThrowable;

} else if (throwable instanceof ConnectException) {

responseThrowable = new ResponseThrowable(throwable, ERROR.NETWORK_ERROR);

responseThrowable.message = “连接失败”;

return responseThrowable;

} else if (throwable instanceof javax.net.ssl.SSLHandshakeException) {

responseThrowable = new ResponseThrowable(throwable, ERROR.SSL_ERROR);

responseThrowable.message = “证书验证失败”;

return responseThrowable;

} else if (throwable instanceof ConnectTimeoutExce

  • 4
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值