Search in sources :

Example 1 with AppCrashHandler

use of com.example.test.andlang.log.AppCrashHandler in project AndLang by wugemu.

the class RequestCacheI method intercept.

@Override
public Response intercept(Chain chain) throws IOException {
    Request request = chain.request();
    Response response = null;
    // --- 重试机制 start
    int count = 0;
    IOException exc = null;
    while (count < maxRetry) {
        try {
            // 发起网络请求
            response = chain.proceed(request);
            // 得到结果跳出循环
            break;
        } catch (IOException exception) {
            count++;
            // 记录异常
            exc = exception;
            if (exception != null) {
                try {
                    String msg = "请求将进行重试----" + exception.toString() + "----" + request.toString();
                    LogUtil.e(msg);
                    // 保存日志
                    AppCrashHandler crashHandler = AppCrashHandler.getInstance();
                    if (crashHandler != null) {
                        crashHandler.saveReqInfo2File(exc.getCause(), msg);
                    }
                } catch (Exception e) {
                    LogUtil.e("网络请求日志记录异常----" + e.toString());
                }
                // 重试
                if (exception instanceof UnknownHostException) {
                    // Unknown host 时等待2s重试
                    try {
                        Thread.sleep(2000);
                    } catch (Exception e) {
                    }
                    continue;
                } else {
                    // 其它异常无需等待 立即重试
                    continue;
                }
            }
            break;
        }
    }
    if (response == null) {
        // 网络请求失败 走本地缓存逻辑
        request = request.newBuilder().cacheControl(CacheControl.FORCE_CACHE).build();
        response = chain.proceed(request);
        int code = response.code();
        if (code == 504) {
            // 网络请求失败 又未命中缓存
            if (exc != null) {
                throw exc;
            } else {
                throw new IOException("未知异常...");
            }
        }
    }
    if (response.networkResponse() != null) {
        LogUtil.e("从网络获取数据:" + request.toString());
    } else if (response.cacheResponse() != null) {
        LogUtil.e("从本地缓存获取数据:" + request.toString());
    }
    return response;
}
Also used : Response(okhttp3.Response) AppCrashHandler(com.example.test.andlang.log.AppCrashHandler) UnknownHostException(java.net.UnknownHostException) Request(okhttp3.Request) IOException(java.io.IOException) IOException(java.io.IOException) UnknownHostException(java.net.UnknownHostException)

Example 2 with AppCrashHandler

use of com.example.test.andlang.log.AppCrashHandler in project AndLang by wugemu.

the class HttpU method onMyResponse.

public void onMyResponse(final Response response, final Context context, String url, final HttpCallback callback, final Request request) {
    try {
        final String result = response.body().string();
        List<String> cookies = response.headers("Set-Cookie");
        String cookie = null;
        for (String str : cookies) {
            if (str.contains("JSSIONID=")) {
                int start = str.indexOf("JSSIONID=");
                int end = str.indexOf(";");
                cookie = Des3.encode(str.substring(start, end));
                BaseLangApplication.getInstance().getSpUtil().putString(context, COOKIE, cookie);
            }
        }
        if (BaseLangUtil.isApkInDebug()) {
            AppCrashHandler crashHandler = AppCrashHandler.getInstance();
            if (crashHandler != null) {
                crashHandler.saveLogInfo2File("返回报文Host:" + url);
                crashHandler.saveLogInfo2File("返回报文cookie:" + cookie);
                crashHandler.saveLogInfo2File("返回报文body:" + result);
            }
        }
        try {
            JSONObject jsonObject = new JSONObject(result);
            final int code = jsonObject.getInt("code");
            if (code == 401) {
                handler.post(new Runnable() {

                    @Override
                    public void run() {
                        callback.loginFail();
                        callback.onAfter();
                    }
                });
            } else if (code == 200) {
                try {
                    if (jsonObject.getLong("nowTime") > 0) {
                        BaseLangApplication.NOW_TIME = jsonObject.getLong("nowTime");
                    }
                    final String msg = jsonObject.getString("message");
                    if (!BaseLangUtil.isEmpty(msg) && context != null) {
                        // 有message toast
                        handler.post(new Runnable() {

                            @Override
                            public void run() {
                                ToastUtil.show(context, msg);
                            }
                        });
                    }
                } catch (Exception e) {
                }
                // 正常返回
                handler.post(new Runnable() {

                    @Override
                    public void run() {
                        callback.onResponse(result);
                        callback.onAfter();
                    }
                });
            } else if (code == 20001 || code == 200002) {
                // 数据不存在
                handler.post(new Runnable() {

                    @Override
                    public void run() {
                        callback.errorCode(code);
                        callback.onAfter();
                    }
                });
            } else {
                // 不是401 200
                final String msg = jsonObject.getString("message");
                if (!BaseLangUtil.isEmpty(msg)) {
                    // 有message toast
                    handler.post(new Runnable() {

                        @Override
                        public void run() {
                            if (context != null) {
                                ToastUtil.show(context, msg);
                            }
                            callback.onAfter();
                        }
                    });
                } else {
                    // 服务器异常
                    handler.post(new Runnable() {

                        @Override
                        public void run() {
                            callback.onError(request, null, code);
                            callback.onAfter();
                        }
                    });
                }
            }
        } catch (final Exception e) {
            // code 不存在
            handler.post(new Runnable() {

                @Override
                public void run() {
                    callback.onError(request, e, -1);
                    callback.onAfter();
                }
            });
        }
    } catch (final Exception e) {
        e.printStackTrace();
        handler.post(new Runnable() {

            @Override
            public void run() {
                callback.onError(request, e, -1);
                callback.onAfter();
            }
        });
    }
}
Also used : AppCrashHandler(com.example.test.andlang.log.AppCrashHandler) JSONObject(org.json.JSONObject) MalformedURLException(java.net.MalformedURLException) IOException(java.io.IOException)

Example 3 with AppCrashHandler

use of com.example.test.andlang.log.AppCrashHandler in project AndLang by wugemu.

the class HttpU method post.

/**
 * 网络请求方法
 *
 * @param context
 * @param url
 * @param params
 * @param tag
 * @param callback
 */
public void post(final Context context, final String url, Map<String, Object> params, Object tag, final HttpCallback callback) {
    if (context == null) {
        callback.onAfter();
        return;
    }
    // token校验参数
    if (params == null) {
        params = new HashMap<String, Object>();
    }
    FormBody.Builder formBuilder = new FormBody.Builder();
    if (params.size() > 0) {
        Iterator iter = params.entrySet().iterator();
        while (iter.hasNext()) {
            Map.Entry entry = (Map.Entry) iter.next();
            if (entry != null) {
                if (entry.getKey() != null && entry.getValue() != null) {
                    formBuilder.add(entry.getKey().toString(), entry.getValue().toString());
                }
            }
        }
    }
    FormBody formBody = formBuilder.build();
    String cookie = BaseLangApplication.getInstance().getSpUtil().getString(context, COOKIE);
    if (cookie != null && !"".equals(cookie)) {
        try {
            cookie = Des3.decode(cookie);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    Request.Builder requestBuilder = new Request.Builder();
    if (cookie != null) {
        requestBuilder.header(COOKIE, cookie);
    }
    final Request request = requestBuilder.url(url).post(formBody).tag(url).build();
    if (BaseLangUtil.isApkInDebug()) {
        AppCrashHandler crashHandler = AppCrashHandler.getInstance();
        if (crashHandler != null) {
            crashHandler.saveLogInfo2File("post请求报文Host:" + url);
            crashHandler.saveLogInfo2File("post请求报文cookie:" + cookie);
            crashHandler.saveLogInfo2File("post请求报文body:" + params);
        }
    }
    callback.onBefore(request);
    Call call = mOkHttpClient.newCall(request);
    call.enqueue(new Callback() {

        @Override
        public void onFailure(Call call, final IOException e) {
            onMyFailure(callback, request, e);
        }

        @Override
        public void onResponse(Call call, final Response response) throws IOException {
            onMyResponse(response, context, url, callback, request);
        }
    });
}
Also used : Call(okhttp3.Call) FormBody(okhttp3.FormBody) Request(okhttp3.Request) IOException(java.io.IOException) MalformedURLException(java.net.MalformedURLException) IOException(java.io.IOException) Response(okhttp3.Response) AppCrashHandler(com.example.test.andlang.log.AppCrashHandler) Callback(okhttp3.Callback) Iterator(java.util.Iterator) JSONObject(org.json.JSONObject) Map(java.util.Map) HashMap(java.util.HashMap) MimeTypeMap(android.webkit.MimeTypeMap)

Example 4 with AppCrashHandler

use of com.example.test.andlang.log.AppCrashHandler in project AndLang by wugemu.

the class BaseLangApplication method initData.

// private RefWatcher setupLeakCanary() {
// if (LeakCanary.isInAnalyzerProcess(this)) {
// return RefWatcher.DISABLED;
// }
// return LeakCanary.install(this);
// }
// public static RefWatcher getRefWatcher(Context context) {
// BaseLangApplication leakApplication = (BaseLangApplication) context.getApplicationContext();
// return leakApplication.refWatcher;
// }
private void initData() {
    mApp = this;
    // 程序错误日志信息收集
    logDir = Environment.getExternalStorageDirectory().getPath() + "/sudian/crash/";
    AppCrashHandler crashHandler = AppCrashHandler.getInstance();
    crashHandler.init(getApplicationContext());
    Logger.addLogAdapter(new AndroidLogAdapter());
    initImageLoad();
    LogUtil.e("0.0", "版本号:V" + VersionUtil.getVersionName(BaseLangApplication.this));
    // 最大化防止应用crash  需要在清单中注册DebugSafeModeTipActivity
    installCockroach();
}
Also used : AppCrashHandler(com.example.test.andlang.log.AppCrashHandler) AndroidLogAdapter(com.orhanobut.logger.AndroidLogAdapter)

Example 5 with AppCrashHandler

use of com.example.test.andlang.log.AppCrashHandler in project AndLang by wugemu.

the class HttpU method get.

/**
 * 网络请求方法
 *
 * @param context
 * @param url
 * @param callback
 */
public void get(final Context context, String url, Map<String, Object> params, final HttpCallback callback) {
    if (context == null) {
        callback.onAfter();
        return;
    }
    // token校验参数
    if (params == null) {
        params = new HashMap<String, Object>();
    }
    String paramStr = "";
    if (params != null && params.size() > 0) {
        Iterator iter = params.entrySet().iterator();
        while (iter.hasNext()) {
            Map.Entry entry = (Map.Entry) iter.next();
            if (entry != null) {
                if (entry.getKey() != null && entry.getValue() != null) {
                    paramStr += entry.getKey() + "=" + entry.getValue() + "&";
                }
            }
        }
    }
    if (!BaseLangUtil.isEmpty(paramStr)) {
        paramStr = paramStr.substring(0, paramStr.length() - 1);
        if (!url.contains("?")) {
            url += "?" + paramStr;
        } else {
            url += "&" + paramStr;
        }
    }
    final String reqUrl = url;
    String cookie = BaseLangApplication.getInstance().getSpUtil().getString(context, COOKIE);
    if (cookie != null && !"".equals(cookie)) {
        try {
            cookie = Des3.decode(cookie);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    Request.Builder requestBuilder = new Request.Builder();
    if (cookie != null) {
        requestBuilder.header(COOKIE, cookie);
    }
    if (BaseLangUtil.isApkInDebug()) {
        AppCrashHandler crashHandler = AppCrashHandler.getInstance();
        if (crashHandler != null) {
            crashHandler.saveLogInfo2File("get请求报文Host:" + reqUrl);
            crashHandler.saveLogInfo2File("get请求报文cookie:" + cookie);
            crashHandler.saveLogInfo2File("get请求报文body:" + params);
        }
    }
    final Request request = requestBuilder.url(reqUrl).build();
    callback.onBefore(request);
    Call call = mOkHttpClient.newCall(request);
    call.enqueue(new Callback() {

        @Override
        public void onFailure(Call call, final IOException e) {
            onMyFailure(callback, request, e);
        }

        @Override
        public void onResponse(Call call, final Response response) throws IOException {
            onMyResponse(response, context, reqUrl, callback, request);
        }
    });
}
Also used : Call(okhttp3.Call) Request(okhttp3.Request) IOException(java.io.IOException) MalformedURLException(java.net.MalformedURLException) IOException(java.io.IOException) Response(okhttp3.Response) AppCrashHandler(com.example.test.andlang.log.AppCrashHandler) Callback(okhttp3.Callback) Iterator(java.util.Iterator) JSONObject(org.json.JSONObject) Map(java.util.Map) HashMap(java.util.HashMap) MimeTypeMap(android.webkit.MimeTypeMap)

Aggregations

AppCrashHandler (com.example.test.andlang.log.AppCrashHandler)5 IOException (java.io.IOException)4 MalformedURLException (java.net.MalformedURLException)3 Request (okhttp3.Request)3 Response (okhttp3.Response)3 JSONObject (org.json.JSONObject)3 MimeTypeMap (android.webkit.MimeTypeMap)2 HashMap (java.util.HashMap)2 Iterator (java.util.Iterator)2 Map (java.util.Map)2 Call (okhttp3.Call)2 Callback (okhttp3.Callback)2 AndroidLogAdapter (com.orhanobut.logger.AndroidLogAdapter)1 UnknownHostException (java.net.UnknownHostException)1 FormBody (okhttp3.FormBody)1