From 23d346b0716d07abdb8ee71ff086f4e1abd60f4c Mon Sep 17 00:00:00 2001 From: DesignQu <250533855@qq.com> Date: Tue, 15 May 2018 12:16:42 +0800 Subject: [PATCH] =?UTF-8?q?1=E3=80=81=E4=BF=AE=E6=94=B9=E9=83=A8=E5=88=86?= =?UTF-8?q?=E6=A0=B8=E5=BF=83=E5=8C=85=E5=90=8D=E5=8F=8A=E7=B1=BB=E5=90=8D?= =?UTF-8?q?=E7=A7=B0=202=E3=80=81=E5=AE=8C=E5=96=84=E9=83=A8=E5=88=86?= =?UTF-8?q?=E6=B3=A8=E9=87=8A=203=E3=80=81=E6=A1=86=E6=9E=B6=E5=A2=9E?= =?UTF-8?q?=E5=8A=A0=E6=97=A5=E5=BF=97=E6=A8=A1=E5=9D=97=EF=BC=8C=E6=8F=90?= =?UTF-8?q?=E4=BE=9B=E6=89=A9=E5=B1=95=E5=BC=80=E5=85=B3=E6=8E=A5=E5=8F=A3?= =?UTF-8?q?=204=E3=80=81=E5=A2=9E=E5=8A=A0=E5=85=A8=E5=B1=80=E9=94=99?= =?UTF-8?q?=E8=AF=AF=E5=9B=9E=E8=B0=83=E6=8E=A5=E5=8F=A3=20AppModule.Globa?= =?UTF-8?q?lErrorHandler=EF=BC=8C=E5=8F=AF=E4=BB=A5=E9=80=9A=E8=BF=87=20Ap?= =?UTF-8?q?pComponent=20=E8=8E=B7=E5=8F=96=EF=BC=8C=E6=AD=A4=E6=8E=A5?= =?UTF-8?q?=E5=8F=A3=E4=B8=8D=E9=99=90=E4=BA=8E=E5=8F=AA=E5=A4=84=E7=90=86?= =?UTF-8?q?=20HTTP=20=E5=BC=82=E5=B8=B8=EF=BC=8C=E5=85=B6=E4=BB=96?= =?UTF-8?q?=E6=A8=A1=E5=9D=97=E4=B9=9F=E5=8F=AF=E4=BB=A5=E5=9B=9E=E8=B0=83?= =?UTF-8?q?=E6=AD=A4=E6=8E=A5=E5=8F=A3=E6=9D=A5=E5=A4=84=E7=90=86=E7=BB=9F?= =?UTF-8?q?=E4=B8=80=E5=BC=82=E5=B8=B8=E7=AE=A1=E7=90=86=205=E3=80=81?= =?UTF-8?q?=E5=AE=8C=E5=96=84=20Demo?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../me/mvp/demo/app/AppConfiguration.java | 150 ++---------------- .../demo/app/config/GlobalErrorConfig.java | 57 +++++++ .../me/mvp/demo/app/config/GsonConfig.java | 22 +++ .../app/config/NetworkInterceptorConfig.java | 65 ++++++++ .../me/mvp/demo/app/config/OkHttpConfig.java | 19 +++ .../config/ParameterInterceptorConfig.java | 34 ++++ .../mvp/demo/app/config/RetrofitConfig.java | 17 ++ .../me/mvp/demo/app/config/RxCacheConfig.java | 18 +++ .../java/me/mvp/demo/mvp/WelcomeActivity.java | 4 +- .../me/mvp/demo/mvp/login/LoginPresenter.java | 5 +- .../me/mvp/demo/mvp/main/MainActivity.java | 3 + .../mvp/frame/di/component/AppComponent.java | 3 + .../mvp/frame/di/module/AppConfigModule.java | 18 +-- .../me/mvp/frame/di/module/AppModule.java | 15 +- .../me/mvp/frame/http/ResponseCallback.java | 9 +- .../frame/http/exception/ApiException.java | 44 ----- .../frame/http/exception/CodeException.java | 18 --- .../http/exception/FactoryException.java | 83 ---------- .../interceptor/ParameterInterceptor.java | 31 +--- .../main/java/me/mvp/frame/package-info.java | 5 +- 20 files changed, 285 insertions(+), 335 deletions(-) create mode 100644 App/src/main/java/me/mvp/demo/app/config/GlobalErrorConfig.java create mode 100644 App/src/main/java/me/mvp/demo/app/config/GsonConfig.java create mode 100644 App/src/main/java/me/mvp/demo/app/config/NetworkInterceptorConfig.java create mode 100644 App/src/main/java/me/mvp/demo/app/config/OkHttpConfig.java create mode 100644 App/src/main/java/me/mvp/demo/app/config/ParameterInterceptorConfig.java create mode 100644 App/src/main/java/me/mvp/demo/app/config/RetrofitConfig.java create mode 100644 App/src/main/java/me/mvp/demo/app/config/RxCacheConfig.java delete mode 100644 Common/src/main/java/me/mvp/frame/http/exception/ApiException.java delete mode 100644 Common/src/main/java/me/mvp/frame/http/exception/CodeException.java delete mode 100644 Common/src/main/java/me/mvp/frame/http/exception/FactoryException.java diff --git a/App/src/main/java/me/mvp/demo/app/AppConfiguration.java b/App/src/main/java/me/mvp/demo/app/AppConfiguration.java index 0bd6772..b2ec143 100644 --- a/App/src/main/java/me/mvp/demo/app/AppConfiguration.java +++ b/App/src/main/java/me/mvp/demo/app/AppConfiguration.java @@ -7,29 +7,27 @@ import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; -import io.rx_cache2.internal.RxCache; import me.mvp.demo.BuildConfig; import me.mvp.demo.app.api.Api; -import me.mvp.demo.app.utils.gson.GsonResponseDeserializer; +import me.mvp.demo.app.config.GlobalErrorConfig; +import me.mvp.demo.app.config.GsonConfig; +import me.mvp.demo.app.config.NetworkInterceptorConfig; +import me.mvp.demo.app.config.OkHttpConfig; +import me.mvp.demo.app.config.ParameterInterceptorConfig; +import me.mvp.demo.app.config.RetrofitConfig; +import me.mvp.demo.app.config.RxCacheConfig; import me.mvp.demo.entity.User; import me.mvp.demo.mvp.login.LoginActivity; -import com.google.gson.GsonBuilder; import com.squareup.leakcanary.LeakCanary; import com.squareup.leakcanary.RefWatcher; import me.mvp.frame.base.App; import me.mvp.frame.base.delegate.ApplicationLifecycles; import me.mvp.frame.di.module.AppConfigModule; -import me.mvp.frame.di.module.AppModule; -import me.mvp.frame.di.module.HttpModule; -import me.mvp.frame.http.NetworkInterceptorHandler; -import me.mvp.frame.http.ResponseEntity; -import me.mvp.frame.http.cookie.PersistentCookieJar; import me.mvp.frame.http.download.Downloader; import me.mvp.frame.http.download.config.DownloaderConfiguration; import me.mvp.frame.http.interceptor.NetworkInterceptor; -import me.mvp.frame.http.interceptor.ParameterInterceptor; import me.mvp.frame.integration.ConfigModule; import me.mvp.frame.utils.AppUtils; import me.mvp.frame.utils.GsonUtils; @@ -37,17 +35,8 @@ import me.mvp.frame.utils.ProjectUtils; import java.io.File; -import java.util.HashMap; import java.util.List; -import okhttp3.Cookie; -import okhttp3.HttpUrl; -import okhttp3.Interceptor; -import okhttp3.OkHttpClient; -import okhttp3.Request; -import okhttp3.Response; -import retrofit2.Retrofit; - /** * 全局配置信息在此配置,需要将此实现类声明到 AndroidManifest 中 */ @@ -64,124 +53,13 @@ public void applyOptions(final Context context, AppConfigModule.Builder builder) builder .httpUrl(Api.APP_DOMAIN) .cacheFile(new File(ProjectUtils.CACHE)) - .networkInterceptorHandler(new NetworkInterceptorHandler() { // Http全局响应结果的处理类 - - @Override - public Request onHttpRequest(Interceptor.Chain chain, Request request) { - // 请求服务器之前可以拿到Request,做一些操作比如给Request统一添加Token或者Header,不做任务操作则直接返回Request - // return chain.request().newBuilder().header("token", tokenId).build(); - return request; - } - - @Override - public Response onHttpResponse(String result, Interceptor.Chain chain, Request request, Response response) { - // 这里提前拿到Http请求结果,可以用来检测,如Token是否过期 -// if (!TextUtils.isEmpty(result)) { -// ResponseEntity entity = GsonUtils.getEntity(result, ResponseEntity.class); -// -// // 登录超时或授权失效,重新获取授权 -// if (entity.getCode() == -253 || entity.getCode() == -254) { -// AppComponent component = ((App) context).getAppComponent(); -// -// // 读取当前登录用户信息 -// String value = PreferencesUtils.getString(context, LoginActivity.class.getName(), null); -// if (value != null) { -// User user = GsonUtils.getEntity(value, User.class); -// -// Call> apiToken = component.getRepositoryManager().obtainApiService(ApiCommon.class).getToken("CF2QCXW6", DeviceUtils.getIMEI(context), user.getUserId()); -// try { -// JsonObject resultToken = apiToken.execute().body().getData(); -// apiToken.execute().body(); -//// Logg.e(resultToken); -//// Logg.e(resultToken.get("access_token")); -// String token = resultToken.get("access_token").getAsString(); -//// Logg.e(token); -// -// HttpUrl.Builder modifiedUrl = request.url().newBuilder() -// .scheme(request.url().scheme()) -// .host(request.url().host()); -// -// modifiedUrl.addQueryParameter("access_token", token); -// -// Request newRequest = request.newBuilder() -//// .method(request.method(), request.body()) -//// .url(modifiedUrl.build()) -// .build(); -// response.body().close(); -// return chain.proceed(newRequest); -// } catch (IOException e) { -// e.printStackTrace(); -// } -// } -// } -// } - - return response; - } - }) - .interceptors(new Interceptor[] - { - new ParameterInterceptor(new ParameterInterceptor.ParameterCallback() { - - /** - * 这里为接口添加类型为HashMap的统一参数,例如Token、版本号等。支持Get、Post方法,ParameterInterceptor会自动判断 - */ - @Override - public HashMap parameters() { - User user = (User) ((App) context).getAppComponent().extras().get(LoginActivity.class.getName()); - - HashMap parameters = new HashMap<>(); - if (user != null) { - // 为接口统一添加access_token参数 - parameters.put("access_token", user.getToken()); - } - - return parameters; - } - }) - }) - .retrofitConfiguration(new HttpModule.RetrofitConfiguration() {// 扩展自定义配置Retrofit参数 - - @Override - public void configRetrofit(Context context, Retrofit.Builder builder) { - - } - }) - .okHttpConfiguration(new HttpModule.OkHttpConfiguration() {// 扩展自定义配置OkHttp参数 - @Override - public void configOkHttp(Context context, OkHttpClient.Builder builder) { - // 配置 HTTPS - // builder.sslSocketFactory(SSL.createSSLSocketFactory(), new TrustAllX509TrustManager()); - // builder.hostnameVerifier(new TrustAllHostnameVerifier()); - } - }) - .rxCacheConfiguration(new HttpModule.RxCacheConfiguration() { - @Override - public RxCache configRxCache(Context context, RxCache.Builder builder) { - // 想自定义 RxCache 的缓存文件夹或者解析方式,如改成 fastjson,请 return rxCacheBuilder.persistence(cacheDirectory, new FastJsonSpeaker()); - return null; - } - }) - .gsonConfiguration(new AppModule.GsonConfiguration() {// 扩展自定义配置Gson参数 - @Override - public void configGson(Context context, GsonBuilder builder) { - builder - .serializeNulls()// 支持序列化null的参数 - .registerTypeAdapter(ResponseEntity.class, new GsonResponseDeserializer()); - } - }) - .cookieLoadForRequest(new PersistentCookieJar.CookieLoadForRequest() { - - @Override - public void saveFromResponse(HttpUrl url, List cookies) { - - } - - @Override - public List loadForRequest(List cookies) { - return cookies; - } - }) + .networkInterceptorHandler(new NetworkInterceptorConfig()) + .interceptors(new ParameterInterceptorConfig(context)) + .retrofitConfiguration(new RetrofitConfig()) + .okHttpConfiguration(new OkHttpConfig()) + .globalErrorHandler(new GlobalErrorConfig()) + .rxCacheConfiguration(new RxCacheConfig()) + .gsonConfiguration(new GsonConfig()) ; } diff --git a/App/src/main/java/me/mvp/demo/app/config/GlobalErrorConfig.java b/App/src/main/java/me/mvp/demo/app/config/GlobalErrorConfig.java new file mode 100644 index 0000000..ae5ea72 --- /dev/null +++ b/App/src/main/java/me/mvp/demo/app/config/GlobalErrorConfig.java @@ -0,0 +1,57 @@ +package me.mvp.demo.app.config; + +import android.content.Context; +import android.net.ParseException; + +import com.google.gson.JsonParseException; + +import org.json.JSONException; + +import java.net.ConnectException; +import java.net.SocketTimeoutException; +import java.net.UnknownHostException; + +import me.mvp.frame.di.component.AppComponent; +import me.mvp.frame.di.module.AppModule; +import me.mvp.frame.widget.Toaster; +import retrofit2.HttpException; + +/** + * 全局异常回调,可以不限于只处理 HTTP 异常,其他模块也可以回调此接口来处理统一异常管理 + * 通过 {@link AppComponent#getGlobalErrorHandler()} 获取此接口 + */ +public class GlobalErrorConfig implements AppModule.GlobalErrorHandler { + + @Override + public void httpError(Context context, Throwable throwable) { + // 可以根据不同的错误做不同的逻辑处理 + String message = "未知错误"; + if (throwable instanceof UnknownHostException) { + message = "网络不可用或无法解析该域名"; + } else if (throwable instanceof ConnectException || throwable instanceof SocketTimeoutException) { + message = "请求网络超时或网络连接异常"; + } else if (throwable instanceof HttpException) { + HttpException httpException = (HttpException) throwable; + if (httpException.code() == 500) { + message = "服务器发生错误"; + } else if (httpException.code() == 404) { + message = "请求地址不存在"; + } else if (httpException.code() == 403) { + message = "请求被服务器拒绝"; + } else if (httpException.code() == 307) { + message = "请求被重定向到其他页面"; + } else { + message = httpException.message(); + } + } else if (throwable instanceof JsonParseException || throwable instanceof ParseException || throwable instanceof JSONException) { + message = "数据解析错误"; + } + + Toaster.postMessage(message); + } + + @Override + public void handlerError(Context context, Throwable throwable) { + + } +} \ No newline at end of file diff --git a/App/src/main/java/me/mvp/demo/app/config/GsonConfig.java b/App/src/main/java/me/mvp/demo/app/config/GsonConfig.java new file mode 100644 index 0000000..3c1c549 --- /dev/null +++ b/App/src/main/java/me/mvp/demo/app/config/GsonConfig.java @@ -0,0 +1,22 @@ +package me.mvp.demo.app.config; + +import android.content.Context; + +import com.google.gson.GsonBuilder; + +import me.mvp.demo.app.utils.gson.GsonResponseDeserializer; +import me.mvp.frame.di.module.AppModule; +import me.mvp.frame.http.ResponseEntity; + +/** + * 扩展自定义配置 Gson 参数 + */ +public class GsonConfig implements AppModule.GsonConfiguration { + + @Override + public void configGson(Context context, GsonBuilder builder) { + builder + .serializeNulls()// 支持序列化null的参数 + .registerTypeAdapter(ResponseEntity.class, new GsonResponseDeserializer()); + } +} \ No newline at end of file diff --git a/App/src/main/java/me/mvp/demo/app/config/NetworkInterceptorConfig.java b/App/src/main/java/me/mvp/demo/app/config/NetworkInterceptorConfig.java new file mode 100644 index 0000000..49d8159 --- /dev/null +++ b/App/src/main/java/me/mvp/demo/app/config/NetworkInterceptorConfig.java @@ -0,0 +1,65 @@ +package me.mvp.demo.app.config; + +import me.mvp.frame.http.NetworkInterceptorHandler; +import okhttp3.Interceptor; +import okhttp3.Request; +import okhttp3.Response; + +/** + * Http全局响应结果的处理类 + */ +public class NetworkInterceptorConfig implements NetworkInterceptorHandler { + + @Override + public Request onHttpRequest(Interceptor.Chain chain, Request request) { + // 请求服务器之前可以拿到Request,做一些操作比如给Request统一添加Token或者Header,不做任务操作则直接返回Request + // return chain.request().newBuilder().header("token", tokenId).build(); + return request; + } + + @Override + public Response onHttpResponse(String result, Interceptor.Chain chain, Request request, Response response) { + // 这里提前拿到Http请求结果,可以用来检测,如Token是否过期 +// if (!TextUtils.isEmpty(result)) { +// ResponseEntity entity = GsonUtils.getEntity(result, ResponseEntity.class); +// +// // 登录超时或授权失效,重新获取授权 +// if (entity.getCode() == -253 || entity.getCode() == -254) { +// AppComponent component = ((App) context).getAppComponent(); +// +// // 读取当前登录用户信息 +// String value = PreferencesUtils.getString(context, LoginActivity.class.getName(), null); +// if (value != null) { +// User user = GsonUtils.getEntity(value, User.class); +// +// Call> apiToken = component.getRepositoryManager().obtainApiService(ApiCommon.class).getToken("CF2QCXW6", DeviceUtils.getIMEI(context), user.getUserId()); +// try { +// JsonObject resultToken = apiToken.execute().body().getData(); +// apiToken.execute().body(); +//// Logg.e(resultToken); +//// Logg.e(resultToken.get("access_token")); +// String token = resultToken.get("access_token").getAsString(); +//// Logg.e(token); +// +// HttpUrl.Builder modifiedUrl = request.url().newBuilder() +// .scheme(request.url().scheme()) +// .host(request.url().host()); +// +// modifiedUrl.addQueryParameter("access_token", token); +// +// Request newRequest = request.newBuilder() +//// .method(request.method(), request.body()) +//// .url(modifiedUrl.build()) +// .build(); +// response.body().close(); +// return chain.proceed(newRequest); +// } catch (IOException e) { +// e.printStackTrace(); +// } +// } +// } +// } + + return response; + } +} \ No newline at end of file diff --git a/App/src/main/java/me/mvp/demo/app/config/OkHttpConfig.java b/App/src/main/java/me/mvp/demo/app/config/OkHttpConfig.java new file mode 100644 index 0000000..52fa96a --- /dev/null +++ b/App/src/main/java/me/mvp/demo/app/config/OkHttpConfig.java @@ -0,0 +1,19 @@ +package me.mvp.demo.app.config; + +import android.content.Context; + +import me.mvp.frame.di.module.HttpModule; +import okhttp3.OkHttpClient; + +/** + * 扩展自定义配置 OkHttp 参数 + */ +public class OkHttpConfig implements HttpModule.OkHttpConfiguration { + + @Override + public void configOkHttp(Context context, OkHttpClient.Builder builder) { + // 配置 HTTPS + // builder.sslSocketFactory(SSL.createSSLSocketFactory(), new TrustAllX509TrustManager()); + // builder.hostnameVerifier(new TrustAllHostnameVerifier()); + } +} \ No newline at end of file diff --git a/App/src/main/java/me/mvp/demo/app/config/ParameterInterceptorConfig.java b/App/src/main/java/me/mvp/demo/app/config/ParameterInterceptorConfig.java new file mode 100644 index 0000000..aca6b99 --- /dev/null +++ b/App/src/main/java/me/mvp/demo/app/config/ParameterInterceptorConfig.java @@ -0,0 +1,34 @@ +package me.mvp.demo.app.config; + +import android.content.Context; + +import java.util.HashMap; + +import me.mvp.demo.entity.User; +import me.mvp.demo.mvp.login.LoginActivity; +import me.mvp.frame.base.App; +import me.mvp.frame.http.interceptor.ParameterInterceptor; + +/** + * 这里为接口添加类型为HashMap的统一参数,例如Token、版本号等。支持Get、Post方法,ParameterInterceptor会自动判断 + */ +public class ParameterInterceptorConfig extends ParameterInterceptor { + + private Context context; + + public ParameterInterceptorConfig(Context context) { + this.context = context; + } + + @Override + public HashMap parameters() { + User user = (User) ((App) context).getAppComponent().extras().get(LoginActivity.class.getName()); + + HashMap parameters = new HashMap<>(); + if (user != null) { + // 为接口统一添加access_token参数 + parameters.put("access_token", user.getToken()); + } + return parameters; + } +} diff --git a/App/src/main/java/me/mvp/demo/app/config/RetrofitConfig.java b/App/src/main/java/me/mvp/demo/app/config/RetrofitConfig.java new file mode 100644 index 0000000..4cf7bc3 --- /dev/null +++ b/App/src/main/java/me/mvp/demo/app/config/RetrofitConfig.java @@ -0,0 +1,17 @@ +package me.mvp.demo.app.config; + +import android.content.Context; + +import me.mvp.frame.di.module.HttpModule; +import retrofit2.Retrofit; + +/** + * 扩展自定义配置 Retrofit 参数 + */ +public class RetrofitConfig implements HttpModule.RetrofitConfiguration { + + @Override + public void configRetrofit(Context context, Retrofit.Builder builder) { + + } +} \ No newline at end of file diff --git a/App/src/main/java/me/mvp/demo/app/config/RxCacheConfig.java b/App/src/main/java/me/mvp/demo/app/config/RxCacheConfig.java new file mode 100644 index 0000000..c8c79c2 --- /dev/null +++ b/App/src/main/java/me/mvp/demo/app/config/RxCacheConfig.java @@ -0,0 +1,18 @@ +package me.mvp.demo.app.config; + +import android.content.Context; + +import io.rx_cache2.internal.RxCache; +import me.mvp.frame.di.module.HttpModule; + +/** + * 扩展自定义配置 RxCache 参数 + */ +public class RxCacheConfig implements HttpModule.RxCacheConfiguration { + + @Override + public RxCache configRxCache(Context context, RxCache.Builder builder) { + // 想自定义 RxCache 的缓存文件夹或者解析方式,如改成 fastjson,请 return rxCacheBuilder.persistence(cacheDirectory, new FastJsonSpeaker()); + return null; + } +} \ No newline at end of file diff --git a/App/src/main/java/me/mvp/demo/mvp/WelcomeActivity.java b/App/src/main/java/me/mvp/demo/mvp/WelcomeActivity.java index c6ac358..39c8221 100644 --- a/App/src/main/java/me/mvp/demo/mvp/WelcomeActivity.java +++ b/App/src/main/java/me/mvp/demo/mvp/WelcomeActivity.java @@ -53,8 +53,8 @@ public boolean handleMessage(Message msg) { // 数据库 DBModule.getInstance().init(getApplication()); -// Intent intent = new Intent(WelcomeActivity.this, MainActivity.class); - Intent intent = new Intent(WelcomeActivity.this, LoginActivity.class); + Intent intent = new Intent(WelcomeActivity.this, MainActivity.class); +// Intent intent = new Intent(WelcomeActivity.this, LoginActivity.class); WelcomeActivity.this.startActivity(intent); WelcomeActivity.this.finish(); return false; diff --git a/App/src/main/java/me/mvp/demo/mvp/login/LoginPresenter.java b/App/src/main/java/me/mvp/demo/mvp/login/LoginPresenter.java index 7ca8ca6..9d6c292 100644 --- a/App/src/main/java/me/mvp/demo/mvp/login/LoginPresenter.java +++ b/App/src/main/java/me/mvp/demo/mvp/login/LoginPresenter.java @@ -6,7 +6,6 @@ import me.mvp.frame.frame.Message; import me.mvp.frame.http.ResponseCallback; import me.mvp.frame.http.ResponseEntity; -import me.mvp.frame.http.exception.ApiException; import retrofit2.Call; @@ -44,8 +43,8 @@ protected void onResponse(ResponseEntity body) { } @Override - protected void onFailure(ApiException exception) { - msg.getTarget().showMessage(0, exception.getMessage()); + protected void onFailure(Throwable throwable) { + msg.getTarget().showMessage(0, throwable.getMessage()); } @Override diff --git a/App/src/main/java/me/mvp/demo/mvp/main/MainActivity.java b/App/src/main/java/me/mvp/demo/mvp/main/MainActivity.java index 53c13b3..59eb244 100644 --- a/App/src/main/java/me/mvp/demo/mvp/main/MainActivity.java +++ b/App/src/main/java/me/mvp/demo/mvp/main/MainActivity.java @@ -5,12 +5,15 @@ import android.support.annotation.NonNull; import android.support.v4.content.ContextCompat; +import javax.inject.Inject; + import me.mvp.demo.R; import me.mvp.demo.ui.adapter.MainViewPagerAdapter; import me.mvp.demo.ui.widget.navigation.BottomNavigation; import me.mvp.demo.ui.widget.navigation.BottomNavigationAdapter; import me.mvp.demo.ui.widget.navigation.BottomNavigationViewPager; import me.mvp.frame.base.BaseActivity; +import me.mvp.frame.di.module.AppModule; import me.mvp.frame.frame.IView; import me.mvp.frame.frame.Message; import me.mvp.frame.widget.Snacker; diff --git a/Common/src/main/java/me/mvp/frame/di/component/AppComponent.java b/Common/src/main/java/me/mvp/frame/di/component/AppComponent.java index 542c683..1f96627 100644 --- a/Common/src/main/java/me/mvp/frame/di/component/AppComponent.java +++ b/Common/src/main/java/me/mvp/frame/di/component/AppComponent.java @@ -39,6 +39,9 @@ public interface AppComponent { // OkHttpClient OkHttpClient getOkHttpClient(); + // Global Error + AppModule.GlobalErrorHandler getGlobalErrorHandler(); + // 图片框架 ImageLoader getImageLoader(); diff --git a/Common/src/main/java/me/mvp/frame/di/module/AppConfigModule.java b/Common/src/main/java/me/mvp/frame/di/module/AppConfigModule.java index 3363772..d39b3a6 100644 --- a/Common/src/main/java/me/mvp/frame/di/module/AppConfigModule.java +++ b/Common/src/main/java/me/mvp/frame/di/module/AppConfigModule.java @@ -54,7 +54,7 @@ public class AppConfigModule { private AppModule.GsonConfiguration gsonConfiguration; - private AppModule.HttpErrorListener httpErrorListener; + private AppModule.GlobalErrorHandler globalErrorHandler; private CookieJar cookie; private PersistentCookieJar.CookieLoadForRequest cookieLoadForRequest; @@ -79,7 +79,7 @@ public AppConfigModule(Builder buidler) { this.gsonConfiguration = buidler.gsonConfiguration; - this.httpErrorListener = buidler.httpErrorListener; + this.globalErrorHandler = buidler.globalErrorHandler; this.cacheFactory = buidler.cacheFactory; @@ -167,8 +167,8 @@ CookieJar provideCookieJar(Application application) { @Singleton @Provides - AppModule.HttpErrorListener provideErrorConfiguration() { - return httpErrorListener == null ? AppModule.HttpErrorListener.EMPTY : httpErrorListener; + AppModule.GlobalErrorHandler provideErrorConfiguration() { + return globalErrorHandler == null ? AppModule.GlobalErrorHandler.EMPTY : globalErrorHandler; } @Singleton @@ -232,7 +232,7 @@ public static class Builder { private AppModule.GsonConfiguration gsonConfiguration; // 提供全局错误响应接口,APP的各种错误信息可以统一回调至此接口 - private AppModule.HttpErrorListener httpErrorListener; + private AppModule.GlobalErrorHandler globalErrorHandler; // 框架缓存组件 private Cache.Factory cacheFactory; @@ -280,8 +280,8 @@ public Builder networkInterceptorHandler(NetworkInterceptorHandler networkInterc return this; } - public Builder interceptors(Interceptor[] interceptors) { - this.interceptors = Arrays.asList(interceptors); + public Builder interceptors(Interceptor interceptor) { + this.interceptors.add(interceptor); return this; } @@ -310,8 +310,8 @@ public Builder gsonConfiguration(AppModule.GsonConfiguration gsonConfiguration) return this; } - public Builder httpErrorListener(AppModule.HttpErrorListener httpErrorListener) { - this.httpErrorListener = httpErrorListener; + public Builder globalErrorHandler(AppModule.GlobalErrorHandler globalErrorHandler) { + this.globalErrorHandler = globalErrorHandler; return this; } diff --git a/Common/src/main/java/me/mvp/frame/di/module/AppModule.java b/Common/src/main/java/me/mvp/frame/di/module/AppModule.java index 56f2235..50cbeb7 100644 --- a/Common/src/main/java/me/mvp/frame/di/module/AppModule.java +++ b/Common/src/main/java/me/mvp/frame/di/module/AppModule.java @@ -71,14 +71,21 @@ public void configGson(Context context, GsonBuilder builder) { }; } - public interface HttpErrorListener { + public interface GlobalErrorHandler { - void handleError(Context context, Throwable throwable); + void httpError(Context context, Throwable throwable); - HttpErrorListener EMPTY = new HttpErrorListener() { + void handlerError(Context context, Throwable throwable); + + GlobalErrorHandler EMPTY = new GlobalErrorHandler() { + + @Override + public void httpError(Context context, Throwable throwable) { + + } @Override - public void handleError(Context context, Throwable throwable) { + public void handlerError(Context context, Throwable throwable) { } }; diff --git a/Common/src/main/java/me/mvp/frame/http/ResponseCallback.java b/Common/src/main/java/me/mvp/frame/http/ResponseCallback.java index 166b6f5..4255769 100644 --- a/Common/src/main/java/me/mvp/frame/http/ResponseCallback.java +++ b/Common/src/main/java/me/mvp/frame/http/ResponseCallback.java @@ -1,8 +1,5 @@ package me.mvp.frame.http; -import me.mvp.frame.http.exception.ApiException; -import me.mvp.frame.http.exception.FactoryException; - import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; @@ -17,8 +14,6 @@ public ResponseCallback() { public void onResponse(Call call, Response response) { if (response.isSuccessful()) { onResponse(response.body()); - } else { - onFailure(FactoryException.resolveExcetpion(response.code())); } onFinish(true); @@ -27,7 +22,7 @@ public void onResponse(Call call, Response response) { @Override public void onFailure(Call call, Throwable throwable) { if (!call.isCanceled()) { - onFailure(FactoryException.resolveExcetpion(throwable)); + onFailure(throwable); } onFinish(!call.isCanceled()); @@ -35,7 +30,7 @@ public void onFailure(Call call, Throwable throwable) { protected abstract void onResponse(T body); - protected abstract void onFailure(ApiException exception); + protected abstract void onFailure(Throwable throwable); protected abstract void onFinish(boolean isCanceled); } \ No newline at end of file diff --git a/Common/src/main/java/me/mvp/frame/http/exception/ApiException.java b/Common/src/main/java/me/mvp/frame/http/exception/ApiException.java deleted file mode 100644 index b926e44..0000000 --- a/Common/src/main/java/me/mvp/frame/http/exception/ApiException.java +++ /dev/null @@ -1,44 +0,0 @@ -package me.mvp.frame.http.exception; - -/** - * 统一异常处理 - */ -public class ApiException extends Exception { - - // 错误码 - private int code; - // 显示的信息 - private String message; - - public ApiException() { - super(); - } - - public ApiException(Throwable throwable) { - super(throwable); - } - - public ApiException(Throwable throwable, int code, String message) { - super(message, throwable); - - this.code = code; - this.message = message; - } - - public int getCode() { - return code; - } - - public void setCode(int code) { - this.code = code; - } - - @Override - public String getMessage() { - return message; - } - - public void setMessage(String message) { - this.message = message; - } -} \ No newline at end of file diff --git a/Common/src/main/java/me/mvp/frame/http/exception/CodeException.java b/Common/src/main/java/me/mvp/frame/http/exception/CodeException.java deleted file mode 100644 index 23cdd64..0000000 --- a/Common/src/main/java/me/mvp/frame/http/exception/CodeException.java +++ /dev/null @@ -1,18 +0,0 @@ -package me.mvp.frame.http.exception; - -/** - * 异常类型 - */ -public class CodeException { - - // HTTP异常 - public static final int HTTP_ERROR = 0x1; - // 网络异常 - public static final int NETWORD_ERROR = 0x2; - // Json解析异常 - public static final int JSON_ERROR = 0x3; - // 无法解析该域名 - public static final int UNKOWNHOST_ERROR = 0x4; - // 未知异常 - public static final int UNKNOWN_ERROR = 0x5; -} \ No newline at end of file diff --git a/Common/src/main/java/me/mvp/frame/http/exception/FactoryException.java b/Common/src/main/java/me/mvp/frame/http/exception/FactoryException.java deleted file mode 100644 index 8bb106f..0000000 --- a/Common/src/main/java/me/mvp/frame/http/exception/FactoryException.java +++ /dev/null @@ -1,83 +0,0 @@ -package me.mvp.frame.http.exception; - - -import org.json.JSONException; - -import java.net.ConnectException; -import java.net.SocketTimeoutException; -import java.net.UnknownHostException; -import java.text.ParseException; - -/** - * 异常处理工厂 - */ -public class FactoryException { - - // HTTP异常 - private static final String HTTP_ERROR = "状态码异常非[200..300)"; - // 网络连接异常 - private static final String NETWORD_ERROR = "网络连接异常"; - // Json解析异常 - private static final String JSON_ERROR = "数据解析失败"; - // 无法解析该域名 - private static final String UNKOWNHOST_ERROR = "无法解析该域名"; - // 未知异常 - private static final String UNKNOWN_ERROR = "未知异常"; - - /** - * 解析异常 - * - * @param code - * @return - */ - public static ApiException resolveExcetpion(int code) { - return resolveExcetpion(code, null); - } - - /** - * 解析异常 - * - * @param throwable - * @return - */ - public static ApiException resolveExcetpion(Throwable throwable) { - return resolveExcetpion(-1, throwable); - } - - /** - * 解析异常 - * - * @param code - * @param throwable - * @return - */ - public static ApiException resolveExcetpion(int code, Throwable throwable) { - if (code != -1) {// HTTP异常 - ApiException apiException = new ApiException(); - apiException.setCode(CodeException.HTTP_ERROR); - apiException.setMessage(code + HTTP_ERROR); - return apiException; - } else if (throwable != null) { - ApiException apiException = new ApiException(throwable); - if (throwable instanceof ConnectException || throwable instanceof SocketTimeoutException) {// 网络连接异常 - apiException.setCode(CodeException.NETWORD_ERROR); - apiException.setMessage(NETWORD_ERROR); - } else if (throwable instanceof JSONException || throwable instanceof ParseException) {// Json解析异常 - apiException.setCode(CodeException.JSON_ERROR); - apiException.setMessage(JSON_ERROR); - } else if (throwable instanceof UnknownHostException) {// 无法解析该域名异常 - apiException.setCode(CodeException.UNKOWNHOST_ERROR); - apiException.setMessage(UNKOWNHOST_ERROR); - } else {// 未知异常 - apiException.setCode(CodeException.UNKNOWN_ERROR); - apiException.setMessage(throwable.getMessage()); - } - return apiException; - } else {// 未知异常 - ApiException apiException = new ApiException(); - apiException.setCode(CodeException.UNKNOWN_ERROR); - apiException.setMessage(UNKNOWN_ERROR); - return apiException; - } - } -} \ No newline at end of file diff --git a/Common/src/main/java/me/mvp/frame/http/interceptor/ParameterInterceptor.java b/Common/src/main/java/me/mvp/frame/http/interceptor/ParameterInterceptor.java index 66014ef..96f2971 100644 --- a/Common/src/main/java/me/mvp/frame/http/interceptor/ParameterInterceptor.java +++ b/Common/src/main/java/me/mvp/frame/http/interceptor/ParameterInterceptor.java @@ -9,31 +9,19 @@ import okhttp3.Interceptor; import okhttp3.OkHttpClient; import okhttp3.Request; -import okhttp3.RequestBody; import okhttp3.Response; -import okio.Buffer; /** * 接口共通参数,支持 Get、POST 方式 * 你可以使用 {@link OkHttpClient.Builder#addInterceptor(Interceptor)} 这种方式为接口统一添加共通参数,如版本号、Token 等 */ -public class ParameterInterceptor implements Interceptor { - - private final ParameterCallback callback; - - public ParameterInterceptor() { - this(ParameterCallback.DEFAULT); - } - - public ParameterInterceptor(ParameterCallback callback) { - this.callback = callback; - } +public abstract class ParameterInterceptor implements Interceptor { @Override public Response intercept(Chain chain) throws IOException { Request request = chain.request(); - HashMap parameters = callback.parameters(); + HashMap parameters = parameters(); if (parameters != null && parameters.size() != 0) { if (request.method().equals("GET")) {// 为GET方式统一添加请求参数 HttpUrl.Builder modifiedUrl = request.url().newBuilder() @@ -78,18 +66,7 @@ public Response intercept(Chain chain) throws IOException { } /** - * 实例化 {@link ParameterInterceptor} 拦截器时必须实现此接口并传入构造方法来添加共通参数 + * 子类必须实现此方法来添加共通参数 */ - public interface ParameterCallback { - - HashMap parameters(); - - ParameterCallback DEFAULT = new ParameterCallback() { - - @Override - public HashMap parameters() { - return null; - } - }; - } + protected abstract HashMap parameters(); } \ No newline at end of file diff --git a/Common/src/main/java/me/mvp/frame/package-info.java b/Common/src/main/java/me/mvp/frame/package-info.java index 4d015ac..2ca6f7b 100644 --- a/Common/src/main/java/me/mvp/frame/package-info.java +++ b/Common/src/main/java/me/mvp/frame/package-info.java @@ -19,7 +19,8 @@ *

* 1、修改部分核心包名及类名称 * 2、完善部分注释 - * 3、底层框架增加日志模块,并提供对外扩展接口 - * 4、完善 Demo + * 3、框架增加日志模块,提供扩展开关接口 + * 4、增加全局错误回调接口 AppModule.GlobalErrorHandler,可以通过 AppComponent 获取,此接口不限于只处理 HTTP 异常,其他模块也可以回调此接口来处理统一异常管理 + * 5、完善 Demo */ package me.mvp.frame; \ No newline at end of file