打造终极MVP+Retrofit2+okhttp3+Rxjava2网络请求,开发实用,简约,由于篇幅字数原因 本章讲解服务器返回类型不统一而引发的解析失败问题,继上篇文章https://www.jianshu.com/p/df4eee78085c,遗留下来的问题,开发中可能会遇到返回内容正常code=1,实体类GSON自动化解析全部内容,当code=0或者其他(也就是数据不是正常展示),可能会出现返回的类型不同意,我们定义的是对象,但是返回的是数组,导致GSON自动化解析失败,在不改后台代码的情况下,前端需要处理,解决办法请往下看
抓住人生中的一分一秒,胜过虚度中的一月一年!
前言
目前最火的网络请求就是Retrofit+okhttp+Rxjava,于是我也加入了使用行列,在网上找了许多案例,实际代码开发中解决了一些所谓的坑,打造出一个使用简约的框架封装,mvp实现模式,实现逻辑如下。
利用了以下技术点
1.Retrofit2 Retrofit2官网
2.okhttp3 okhttp3官网
3.RxJava2 RxJava2官网
4.MVP
下面看下代码结构
1.导包
//网络请求
compile 'com.squareup.okhttp3:okhttp:3.9.1'
compile 'com.squareup.retrofit2:retrofit:2.3.0'
//ConverterFactory的Gson依赖包
compile 'com.squareup.retrofit2:converter-gson:2.3.0'
//CallAdapterFactory的Rx依赖包
compile 'com.squareup.retrofit2:adapter-rxjava2:2.3.0'
compile 'io.reactivex.rxjava2:rxandroid:2.0.2'
2.retrofit代码实现
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.lp.mvp_network.App;
import com.lp.mvp_network.base.BaseContent;
import com.lp.mvp_network.base.convert.MyGsonConverterFactory;
import com.lp.mvp_network.base.cookie.CookieManger;
import com.lp.mvp_network.base.gson.DoubleDefault0Adapter;
import com.lp.mvp_network.base.gson.IntegerDefault0Adapter;
import com.lp.mvp_network.base.gson.LongDefault0Adapter;
import com.orhanobut.logger.Logger;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
/**
* File descripition: 创建Retrofit
*
* @author lp
* @date 2018/6/19
*/
public class ApiRetrofit {
public final String BASE_SERVER_URL = BaseContent.baseUrl;
private String TAG = "ApiRetrofit %s";
private static ApiRetrofit apiRetrofit;
private Retrofit retrofit;
private ApiServer apiServer;
private static Gson gson;
private static final int DEFAULT_TIMEOUT = 15;
public ApiRetrofit() {
OkHttpClient.Builder httpClientBuilder = new OkHttpClient.Builder();
httpClientBuilder
.cookieJar(new CookieManger(App.getContext())) //这块是添加的管理cookie方法
.addInterceptor(interceptor)//日志拦截
// .addInterceptor(new HeadUrlInterceptor())
.connectTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS)
.writeTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS)
.readTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS)
.retryOnConnectionFailure(true);//错误重联
retrofit = new Retrofit.Builder()
.baseUrl(BASE_SERVER_URL)
.addConverterFactory(GsonConverterFactory.create())//添加json转换框架
//支持RxJava2
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.client(httpClientBuilder.build())
.build();
apiServer = retrofit.create(ApiServer.class);
}
public static ApiRetrofit getInstance() {
if (apiRetrofit == null) {
synchronized (Object.class) {
if (apiRetrofit == null) {
apiRetrofit = new ApiRetrofit();
}
}
}
return apiRetrofit;
}
public ApiServer getApiService() {
return apiServer;
}
/**
* 请求访问quest
* response拦截器
*/
private Interceptor interceptor = new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
long startTime = System.currentTimeMillis();
Response response = chain.proceed(chain.request());
long endTime = System.currentTimeMillis();
long duration = endTime - startTime;
MediaType mediaType = response.body().contentType();
String content = response.body().string();
// analyzeJson("data", "", content);
Logger.wtf(TAG, "----------Request Start----------------");
printParams(request.body());
Logger.e(TAG, "| " + request.toString() + "===========" + request.headers().toString());
Logger.json(content);
Logger.e(content);
Logger.wtf(TAG, "----------Request End:" + duration + "毫秒----------");
return response.newBuilder()
.body(ResponseBody.create(mediaType, content))
.build();
}
};
/**
* 请求参数日志打印
*
* @param body
*/
private void printParams(RequestBody body) {
if (body != null) {
Buffer buffer = new Buffer();
try {
body.writeTo(buffer);
Charset charset = Charset.forName("UTF-8");
MediaType contentType = body.contentType();
if (contentType != null) {
charset = contentType.charset(UTF_8);
}
String params = buffer.readString(charset);
Logger.e(TAG, "请求参数: | " + params);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
3.新建ApiServer类,注释的都是请求案例
public interface ApiServer {
//示例 多种类型请求方式
// @POST("api/Activity/get_activities?")
// Observable<BaseModel<List<>>> getApi1(@Query("time") String requestType);
// @GET("api/Activity/get_activities?")
// Observable<BaseModel<List<>>> getApi1(@Query("time") String requestType);
// @FormUrlEncoded
// @POST("api/Activity/get_activities?")
// Observable<BaseModel<List<>>> getApi1(@Field("time") String requestType);
// @FormUrlEncoded
// @POST("api/Activity/get_activities?")
// Observable<BaseModel<List<>>> getApi1(@FieldMap HashMap<String, String> params);
// @Multipart
// @POST("api/Activity/get_activities?")
// Observable<BaseModel<List<>>> getApi1(@PartMap Map<String, RequestBody> map);
@POST("api/Activity/get_activities?")
Observable<BaseModel<List<MainBean>>> getMain(@Query("time") String requestType);
}
解决办法如下
1.在上述第2小步创建retrofit时,给retrofit添加GSON转化框架时,我们需要重写一下gson源码
.addConverterFactory(GsonConverterFactory.create())//添加json转换框架
改成如下我们自己定义的转换框架
.addConverterFactory(MyGsonConverterFactory.create())//
需要重写源码中三个类
第一个类为:MyGsonConverterFactory源码如下(以下内容复制粘贴即可,和源码一样)
import com.google.gson.Gson;
import com.google.gson.TypeAdapter;
import com.google.gson.reflect.TypeToken;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Converter;
import retrofit2.Retrofit;
/**
* File descripition: 重写gson 判断返回值 状态划分
*
* @author lp
* @date 2018/8/24
*/
/**
* A {@linkplain Converter.Factory converter} which uses Gson for JSON.
* <p>
* Because Gson is so flexible in the types it supports, this converter assumes that it can handle
* all types. If you are mixing JSON serialization with something else (such as protocol buffers),
* you must {@linkplain Retrofit.Builder#addConverterFactory(Converter.Factory) add this instance}
* last to allow the other converters a chance to see their types.
*/
public final class MyGsonConverterFactory extends Converter.Factory {
/**
* Create an instance using a default {@link Gson} instance for conversion. Encoding to JSON and
* decoding from JSON (when no charset is specified by a header) will use UTF-8.
*/
public static MyGsonConverterFactory create() {
return create(new Gson());
}
/**
* Create an instance using {@code gson} for conversion. Encoding to JSON and
* decoding from JSON (when no charset is specified by a header) will use UTF-8.
*/
@SuppressWarnings("ConstantConditions") // Guarding public API nullability.
public static MyGsonConverterFactory create(Gson gson) {
if (gson == null) throw new NullPointerException("gson == null");
return new MyGsonConverterFactory(gson);
}
private final Gson gson;
private MyGsonConverterFactory(Gson gson) {
this.gson = gson;
}
@Override
public Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations,
Retrofit retrofit) {
TypeAdapter<?> adapter = gson.getAdapter(TypeToken.get(type));
return new MyGsonResponseBodyConverter<>(gson, adapter);
}
@Override
public Converter<?, RequestBody> requestBodyConverter(Type type,
Annotation[] parameterAnnotations, Annotation[] methodAnnotations, Retrofit retrofit) {
TypeAdapter<?> adapter = gson.getAdapter(TypeToken.get(type));
return new MyGsonRequestBodyConverter<>(gson, adapter);
}
}
第二个类为:MyGsonRequestBodyConverter源码如下(以下内容复制粘贴即可,和源码一样)
import com.google.gson.Gson;
import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.nio.charset.Charset;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import okio.Buffer;
import retrofit2.Converter;
/**
* File descripition: 重写gson 判断返回值 状态划分
*
* @author lp
* @date 2018/8/24
*/
final class MyGsonRequestBodyConverter<T> implements Converter<T, RequestBody> {
private static final MediaType MEDIA_TYPE = MediaType.parse("application/json; charset=UTF-8");
private static final Charset UTF_8 = Charset.forName("UTF-8");
private final Gson gson;
private final TypeAdapter<T> adapter;
MyGsonRequestBodyConverter(Gson gson, TypeAdapter<T> adapter) {
this.gson = gson;
this.adapter = adapter;
}
@Override
public RequestBody convert(T value) throws IOException {
Buffer buffer = new Buffer();
Writer writer = new OutputStreamWriter(buffer.outputStream(), UTF_8);
JsonWriter jsonWriter = gson.newJsonWriter(writer);
adapter.write(jsonWriter, value);
jsonWriter.close();
return RequestBody.create(MEDIA_TYPE, buffer.readByteString());
}
}
第三个类为:MyGsonResponseBodyConverter源码如下(这块需要改写内容)
import com.google.gson.Gson;
import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import com.lp.mvp_network.base.ApiException;
import com.lp.mvp_network.base.BaseContent;
import com.lp.mvp_network.base.BaseResult;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import okhttp3.MediaType;
import okhttp3.ResponseBody;
import retrofit2.Converter;
import static okhttp3.internal.Util.UTF_8;
/**
* File descripition: 重写gson 判断返回值 状态划分
* <p>
* 此处很重要
* 为何这样写:因为开发中有这样的需求 当服务器返回假如0是正常 1是不正常 0我们gson 或 fastJson解析数据
* 1我们不想解析(可能返回值出现以前是对象 数据为空变成了数组等等,于是在不改后台代码的情况下 我们前端需要处理)
* 但是用了插件之后没有很有效的方法控制解析 所以处理方式为 当服务器返回不等于0时候 其他状态都抛出异常 然后提示
*
* @author lp
* @date 2018/8/24
*/
final class MyGsonResponseBodyConverter<T> implements Converter<ResponseBody, T> {
private final Gson gson;
private final TypeAdapter<T> adapter;
MyGsonResponseBodyConverter(Gson gson, TypeAdapter<T> adapter) {
this.gson = gson;
this.adapter = adapter;
}
@Override
public T convert(ResponseBody value) throws IOException {
String response = value.string();
//自定义解析实体类,只解析数据最外层,如code message
BaseResult re = gson.fromJson(response, BaseResult.class);
//关注的重点,自定义响应码中非1的情况,一律抛出ApiException异常。
//这样,我们就成功的将该异常交给onError()去处理了。
if (re.getCode() != BaseContent.basecode) {
value.close();
throw new ApiException(re.getCode(), re.getMessage());
}
//如果是1(数据正常返回),我们正常解析
MediaType mediaType = value.contentType();
Charset charset = mediaType != null ? mediaType.charset(UTF_8) : UTF_8;
ByteArrayInputStream bis = new ByteArrayInputStream(response.getBytes());
InputStreamReader reader = new InputStreamReader(bis, charset);
JsonReader jsonReader = gson.newJsonReader(reader);
try {
return adapter.read(jsonReader);
} finally {
value.close();
}
}
}
再说明一下上边实现逻辑,期间我们拦截解析一步,先定义一个BaseResult,实体类只含code,和message,解析这个实体类内容,拿到code返回值,与后台比对约定好的状态码(比如1是正常),当返回1,我们不做处理,如果返回其他,如0或1001等,我们一律抛出自定义异常处理实体类ApiException,将code和message放进去,到异常里进行逻辑判断,下边贴一下BaseResult,ApiException这俩个类的代码
BaseResult源码如下(这块需要改写为你的项目返回字段名)
/**
* File descripition: 状态划分 基类
*
* @author lp
* @date 2018/8/27
*/
public class BaseResult {
public String message;
public int code;
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
}
ApiException源码如下
/**
* File descripition: 异常处理基类
*
* @author lp
* @date 2018/8/24
*/
public class ApiException extends RuntimeException {
private int errorCode;
public ApiException(int code, String msg) {
super(msg);
this.errorCode = code;
}
public int getErrorCode() {
return errorCode;
}
}
解析处已处理,开始分析抛出的异常内容
__BaseObserver源码如下(为何凭空出现这个类,可看下上篇文章,
https://www.jianshu.com/p/df4eee78085c
如果我们项目结构不同,可采取这种思路处理)__
import com.google.gson.JsonParseException;
import com.lp.mvp_network.base.ApiException;
import com.lp.mvp_network.base.BaseContent;
import com.lp.mvp_network.utils.NetWorkUtils;
import org.json.JSONException;
import java.io.InterruptedIOException;
import java.net.ConnectException;
import java.net.UnknownHostException;
import java.text.ParseException;
import io.reactivex.observers.DisposableObserver;
import retrofit2.HttpException;
/**
* File descripition: 数据处理基类
*
* @author lp
* @date 2018/6/19
*/
public abstract class BaseObserver<T> extends DisposableObserver<T> {
public static final int CODE = BaseContent.basecode;
protected BaseView view;
/**
* 网络连接失败 无网
*/
public static final int NETWORK_ERROR = 100000;
/**
* 解析数据失败
*/
public static final int PARSE_ERROR = 1008;
/**
* 网络问题
*/
public static final int BAD_NETWORK = 1007;
/**
* 连接错误
*/
public static final int CONNECT_ERROR = 1006;
/**
* 连接超时
*/
public static final int CONNECT_TIMEOUT = 1005;
/**
* 未登录 与服务器约定返回的值 这里未登录只是一个案例
*/
public static final int CONNECT_NOT_LOGIN = 1001;
/**
* 其他code 提示
*/
public static final int OTHER_MESSAGE = 20000;
public BaseObserver(BaseView view) {
this.view = view;
}
@Override
protected void onStart() {
if (view != null) {
view.showLoading();
}
}
@Override
public void onNext(T o) {
try {
if (view != null) {
view.hideLoading();
}
BaseModel model = (BaseModel) o;
if (model.getErrcode() == CODE) {
onSuccess(o);
/*服务器返回的指定成功 code 设置是否回调 解开注释回调*//*
if (view != null) {
view.onErrorCode(model);
}*/
} else {
if (view != null) {
view.onErrorCode(model);
}
}
} catch (Exception e) {
e.printStackTrace();
onError(e.toString());
}
}
@Override
public void onError(Throwable e) {
if (view != null) {
view.hideLoading();
}
if (e instanceof HttpException) {
// HTTP错误
onException(BAD_NETWORK, "");
} else if (e instanceof ConnectException
|| e instanceof UnknownHostException) {
// 连接错误
onException(CONNECT_ERROR, "");
} else if (e instanceof InterruptedIOException) {
// 连接超时
onException(CONNECT_TIMEOUT, "");
} else if (e instanceof JsonParseException
|| e instanceof JSONException
|| e instanceof ParseException) {
// 解析错误
onException(PARSE_ERROR, "");
e.printStackTrace();
/**
* 此处很重要
* 为何这样写:因为开发中有这样的需求 当服务器返回假如0是正常 1是不正常 当返回0时:我们gson 或 fastJson解析数据
* 返回1时:我们不想解析(可能返回值出现以前是对象 但是现在数据为空变成了数组等等,于是在不改后台代码的情况下 我们前端需要处理)
* 但是用了插件之后没有很有效的方法控制解析 所以处理方式为 当服务器返回不等于0时候 其他状态都抛出异常 然后提示
* 代码上一级在 MyGsonResponseBodyConverter 中处理 前往查看逻辑
*/
} else if (e instanceof ApiException) {
ApiException exception = (ApiException) e;
int code = exception.getErrorCode();
switch (code) {
//未登录(此处只是案例 供理解)
case CONNECT_NOT_LOGIN:
view.onErrorCode(new BaseModel(exception.getMessage(), code));
onException(CONNECT_NOT_LOGIN, "");
break;
//其他不等于0 的所有状态
default:
onException(OTHER_MESSAGE, exception.getMessage());
view.onErrorCode(new BaseModel(exception.getMessage(), code));
break;
}
} else {
if (e != null) {
onError(e.toString());
} else {
onError("未知错误");
}
}
}
/**
* 中间拦截一步 判断是否有网络 这步判断相对准确 此步去除也可以
*
* @param unknownError
* @param message
*/
private void onException(int unknownError, String message) {
BaseModel model = new BaseModel(message, unknownError);
if (!NetWorkUtils.isAvailableByPing()) {
model.setErrcode(NETWORK_ERROR);
model.setErrmsg("网络不可用,请检查网络连接!");
}
onExceptions(model.getErrcode(), model.getErrmsg());
if (view != null) {
view.onErrorCode(model);
}
}
private void onExceptions(int unknownError, String message) {
switch (unknownError) {
case CONNECT_ERROR:
onError("连接错误");
break;
case CONNECT_TIMEOUT:
onError("连接超时");
break;
case BAD_NETWORK:
onError("网络超时");
break;
case PARSE_ERROR:
onError("数据解析失败");
break;
//未登录
case CONNECT_NOT_LOGIN:
// onError("未登录");
break;
//正常执行 提示信息
case OTHER_MESSAGE:
onError(message);
break;
//网络不可用
case NETWORK_ERROR:
onError("网络不可用,请检查网络连接!");
break;
default:
break;
}
}
//消失写到这 有一定的延迟 对dialog显示有影响
@Override
public void onComplete() {
/* if (view != null) {
view.hideLoading();
}*/
}
public abstract void onSuccess(T o);
public abstract void onError(String msg);
}
说明下解决办法,上边备注也可以看到,在返回onError中,我们判断下是否有返回自定义的异常处理类e instanceof ApiException,如果有把异常转化成 实体类
ApiException exception = (ApiException) e;
int code = exception.getErrorCode();
通过code判断是否进行那种逻辑处理
至此 自定义解析体实现完成
本文章最终实现终极MVP+Retrofit2+okhttp3+Rxjava2网络请求,开发实用,简约,具体实现方式请查看其他几篇文章
github地址:https://github.com/LPTim/mvp
csdn地址:https://download.csdn.net/download/loocanp/10749238
网友评论