網(wǎng)絡請求異常上報

一般情況下app里面接口請求異常了刮便,但是我們沒法搜集到是哪個接口,異常的問題绽慈,哪個數(shù)據(jù)異常等恨旱。
所以我改寫了下攔截器和解析器。
代碼如下坝疼,供參考:

OkHttpClient.Builder builder = new OkHttpClient.Builder();
        if (HcbAppConfig.HCB_ENVIRONMENT_TYPE == 0) {
            builder.dns(OkHttpDns.getInstance(HcbApp.getContext()));
        }
        // 連接超時時間
        builder.connectTimeout(DEFAULT_TIME_OUT, TimeUnit.SECONDS);
        // 寫操作 超時時間
        builder.writeTimeout(DEFAULT_READ_TIME_OUT,TimeUnit.SECONDS);
        // 讀操作超時時間
        builder.readTimeout(DEFAULT_READ_TIME_OUT,TimeUnit.SECONDS);
        builder.addInterceptor(new HcbHttpPublicParamsInterceptor());
        builder.addInterceptor(new MyHttpLoggingInterceptor());
        mRetrofit = new Retrofit.Builder()
                .client(builder.build())
                .baseUrl(HcbAppConfig.HCB_APP_CURRENT_ENVIRONMENT)
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .addConverterFactory(MyGsonConverterFactory.create())
                .build();
package com.hcb.base.app.http;

import android.text.TextUtils;

import com.tencent.bugly.crashreport.CrashReport;

import java.io.EOFException;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.Collections;
import java.util.Set;
import java.util.TreeSet;
import java.util.concurrent.TimeUnit;

import okhttp3.Connection;
import okhttp3.Headers;
import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okhttp3.internal.http.HttpHeaders;
import okhttp3.internal.platform.Platform;
import okio.Buffer;
import okio.BufferedSource;
import okio.GzipSource;

import static okhttp3.internal.platform.Platform.INFO;

/**
 * 請描述使用該類使用方法K严汀!钝凶!
 *
 * @author 陳聰 2020-07-17 16:48
 */
public class MyHttpLoggingInterceptor implements Interceptor {
    private static final Charset UTF8 = Charset.forName("UTF-8");

    public enum Level {
        /** No logs. */
        NONE,
        /**
         * Logs request and response lines.
         *
         * <p>Example:
         * <pre>{@code
         * --> POST /greeting http/1.1 (3-byte body)
         *
         * <-- 200 OK (22ms, 6-byte body)
         * }</pre>
         */
        BASIC,
        /**
         * Logs request and response lines and their respective headers.
         *
         * <p>Example:
         * <pre>{@code
         * --> POST /greeting http/1.1
         * Host: example.com
         * Content-Type: plain/text
         * Content-Length: 3
         * --> END POST
         *
         * <-- 200 OK (22ms)
         * Content-Type: plain/text
         * Content-Length: 6
         * <-- END HTTP
         * }</pre>
         */
        HEADERS,
        /**
         * Logs request and response lines and their respective headers and bodies (if present).
         *
         * <p>Example:
         * <pre>{@code
         * --> POST /greeting http/1.1
         * Host: example.com
         * Content-Type: plain/text
         * Content-Length: 3
         *
         * Hi?
         * --> END POST
         *
         * <-- 200 OK (22ms)
         * Content-Type: plain/text
         * Content-Length: 6
         *
         * Hello!
         * <-- END HTTP
         * }</pre>
         */
        BODY
    }

    public interface Logger {
        void log(String message);

        /** A {@link MyHttpLoggingInterceptor.Logger} defaults output appropriate for the current platform. */
        MyHttpLoggingInterceptor.Logger DEFAULT = new MyHttpLoggingInterceptor.Logger() {
            @Override
            public void log(String message) {
                Platform.get().log(INFO, message, null);
            }
        };
    }

    public MyHttpLoggingInterceptor() {
        this(MyHttpLoggingInterceptor.Logger.DEFAULT);
    }

    public MyHttpLoggingInterceptor(MyHttpLoggingInterceptor.Logger logger) {
        this.logger = logger;
    }

    private final MyHttpLoggingInterceptor.Logger logger;

    private volatile Set<String> headersToRedact = Collections.emptySet();

    public void redactHeader(String name) {
        Set<String> newHeadersToRedact = new TreeSet<>(String.CASE_INSENSITIVE_ORDER);
        newHeadersToRedact.addAll(headersToRedact);
        newHeadersToRedact.add(name);
        headersToRedact = newHeadersToRedact;
    }

    private volatile MyHttpLoggingInterceptor.Level level = MyHttpLoggingInterceptor.Level.NONE;

    /** Change the level at which this interceptor logs. */
    public MyHttpLoggingInterceptor setLevel(MyHttpLoggingInterceptor.Level level) {
        if (level == null) throw new NullPointerException("level == null. Use Level.NONE instead.");
        this.level = level;
        return this;
    }

    public MyHttpLoggingInterceptor.Level getLevel() {
        return level;
    }

    @Override
    public Response intercept(Chain chain) throws IOException {
        MyHttpLoggingInterceptor.Level level = this.level;

        Request request = chain.request();
        if (level == MyHttpLoggingInterceptor.Level.NONE) {
            return chain.proceed(request);
        }

        boolean logBody = level == MyHttpLoggingInterceptor.Level.BODY;
        boolean logHeaders = logBody || level == MyHttpLoggingInterceptor.Level.HEADERS;

        RequestBody requestBody = request.body();
        boolean hasRequestBody = requestBody != null;

        Connection connection = chain.connection();
        String requestStartMessage = "--> "
                + request.method()
                + ' ' + request.url()
                + (connection != null ? " " + connection.protocol() : "");
        if (!logHeaders && hasRequestBody) {
            requestStartMessage += " (" + requestBody.contentLength() + "-byte body)";
        }
        logger.log(requestStartMessage);

        if (logHeaders) {
            if (hasRequestBody) {
                // Request body headers are only present when installed as a network interceptor. Force
                // them to be included (when available) so there values are known.
                if (requestBody.contentType() != null) {
                    logger.log("Content-Type: " + requestBody.contentType());
                }
                if (requestBody.contentLength() != -1) {
                    logger.log("Content-Length: " + requestBody.contentLength());
                }
            }

            Headers headers = request.headers();
            for (int i = 0, count = headers.size(); i < count; i++) {
                String name = headers.name(i);
                // Skip headers from the request body as they are explicitly logged above.
                if (!"Content-Type".equalsIgnoreCase(name) && !"Content-Length".equalsIgnoreCase(name)) {
                    logHeader(headers, i);
                }
            }

            if (!logBody || !hasRequestBody) {
                logger.log("--> END " + request.method());
            } else if (bodyHasUnknownEncoding(request.headers())) {
                logger.log("--> END " + request.method() + " (encoded body omitted)");
            } else {
                Buffer buffer = new Buffer();
                requestBody.writeTo(buffer);

                Charset charset = UTF8;
                MediaType contentType = requestBody.contentType();
                if (contentType != null) {
                    charset = contentType.charset(UTF8);
                }

                logger.log("");
                if (isPlaintext(buffer)) {
                    logger.log(buffer.readString(charset));
                    logger.log("--> END " + request.method()
                            + " (" + requestBody.contentLength() + "-byte body)");
                } else {
                    logger.log("--> END " + request.method() + " (binary "
                            + requestBody.contentLength() + "-byte body omitted)");
                }
            }
        }
        //獲取header,判斷是否標識了需要配置用戶賬號,此邏輯用于登錄注冊等接口中無法獲取手機號上報情況
        Headers mHeaders = request.headers();
        String httpExPhone = "";
        for (int i = 0, count = mHeaders.size(); i < count; i++) {
            String name = mHeaders.name(i);
            if ("Http-ex-phone".equalsIgnoreCase(name)) {
                httpExPhone = mHeaders.value(i);
                if (!TextUtils.isEmpty(httpExPhone)) {
                    if (TextUtils.isEmpty(CrashReport.getUserId()) ||
                            !TextUtils.equals(CrashReport.getUserId(), httpExPhone)) {
                        CrashReport.setUserId(httpExPhone);
                        com.orhanobut.logger.Logger.e("登錄注冊等接口配置上報手機號:" + httpExPhone);
                    }
                }
                break;
            }
        }

        long startNs = System.nanoTime();
        Response response;
        try {
            response = chain.proceed(request);
        } catch (Exception e) {
            logger.log("<-- HTTP FAILED: " + e);
            CrashReport.postCatchedException(new Exception("請求失斠敲ⅰ:" + request.url() + "\n" + e.getMessage()));
            logger.log("請求失敗:" + request.url() + "\n" + e.getMessage());
            throw e;
        }
        long tookMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNs);

        ResponseBody responseBody = response.body();
        long contentLength = responseBody.contentLength();
        String bodySize = contentLength != -1 ? contentLength + "-byte" : "unknown-length";
        logger.log("<-- "
                + response.code()
                + (response.message().isEmpty() ? "" : ' ' + response.message())
                + ' ' + response.request().url()
                + " (" + tookMs + "ms" + (!logHeaders ? ", " + bodySize + " body" : "") + ')');

        if (logHeaders) {
            Headers headers = response.headers();
            for (int i = 0, count = headers.size(); i < count; i++) {
                logHeader(headers, i);
            }

            if (!logBody || !HttpHeaders.hasBody(response)) {
                logger.log("<-- END HTTP");
            } else if (bodyHasUnknownEncoding(response.headers())) {
                logger.log("<-- END HTTP (encoded body omitted)");
            } else {
                BufferedSource source = responseBody.source();
                source.request(Long.MAX_VALUE); // Buffer the entire body.
                Buffer buffer = source.buffer();

                Long gzippedLength = null;
                if ("gzip".equalsIgnoreCase(headers.get("Content-Encoding"))) {
                    gzippedLength = buffer.size();
                    GzipSource gzippedResponseBody = null;
                    try {
                        gzippedResponseBody = new GzipSource(buffer.clone());
                        buffer = new Buffer();
                        buffer.writeAll(gzippedResponseBody);
                    } finally {
                        if (gzippedResponseBody != null) {
                            gzippedResponseBody.close();
                        }
                    }
                }

                Charset charset = UTF8;
                MediaType contentType = responseBody.contentType();
                if (contentType != null) {
                    charset = contentType.charset(UTF8);
                }

                if (!isPlaintext(buffer)) {
                    logger.log("");
                    logger.log("<-- END HTTP (binary " + buffer.size() + "-byte body omitted)");
                    return response;
                }

                if (contentLength != 0) {
                    logger.log("");
                    logger.log(buffer.clone().readString(charset));
                }

                if (gzippedLength != null) {
                    logger.log("<-- END HTTP (" + buffer.size() + "-byte, "
                            + gzippedLength + "-gzipped-byte body)");
                } else {
                    logger.log("<-- END HTTP (" + buffer.size() + "-byte body)");
                }
            }
        }
        if (!response.isSuccessful()) {
            CrashReport.postCatchedException(new Exception("請求失敗:" + request.url() + "\n狀態(tài)碼:" + response.code()));
        }
        Response.Builder builder = response.newBuilder();
        MyResponseBody myResponseBody = MyResponseBody.create(responseBody.contentType(), responseBody.string());
        myResponseBody.url = request.url().url().toString();
        builder.body(myResponseBody);
        return builder.build();
    }

    private void logHeader(Headers headers, int i) {
        String value = headersToRedact.contains(headers.name(i)) ? "██" : headers.value(i);
        logger.log(headers.name(i) + ": " + value);
    }

    /**
     * Returns true if the body in question probably contains human readable text. Uses a small sample
     * of code points to detect unicode control characters commonly used in binary file signatures.
     */
    static boolean isPlaintext(Buffer buffer) {
        try {
            Buffer prefix = new Buffer();
            long byteCount = buffer.size() < 64 ? buffer.size() : 64;
            buffer.copyTo(prefix, 0, byteCount);
            for (int i = 0; i < 16; i++) {
                if (prefix.exhausted()) {
                    break;
                }
                int codePoint = prefix.readUtf8CodePoint();
                if (Character.isISOControl(codePoint) && !Character.isWhitespace(codePoint)) {
                    return false;
                }
            }
            return true;
        } catch (EOFException e) {
            return false; // Truncated UTF-8 sequence.
        }
    }

    private static boolean bodyHasUnknownEncoding(Headers headers) {
        String contentEncoding = headers.get("Content-Encoding");
        return contentEncoding != null
                && !contentEncoding.equalsIgnoreCase("identity")
                && !contentEncoding.equalsIgnoreCase("gzip");
    }
}
package com.hcb.base.app.http;

import com.google.gson.Gson;
import com.google.gson.JsonIOException;
import com.google.gson.TypeAdapter;
import com.google.gson.reflect.TypeToken;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonToken;
import com.google.gson.stream.JsonWriter;
import com.tencent.bugly.crashreport.CrashReport;

import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Type;
import java.nio.charset.Charset;

import okhttp3.MediaType;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import okio.Buffer;
import retrofit2.Converter;
import retrofit2.Retrofit;

/**
 * gson解析類掂名,自定義用于收集異常信息
 *
 * @author 陳聰 2020-07-20 09:20
 */
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 GsonResponseBodyConverter<>(gson, adapter);
    }

    @Override
    public Converter<?, RequestBody> requestBodyConverter(Type type,
                                                          Annotation[] parameterAnnotations, Annotation[] methodAnnotations, Retrofit retrofit) {
        TypeAdapter<?> adapter = gson.getAdapter(TypeToken.get(type));
        return new GsonRequestBodyConverter<>(gson, adapter);
    }

    final class GsonResponseBodyConverter<T> implements Converter<ResponseBody, T> {
        private final Gson gson;
        private final TypeAdapter<T> adapter;

        GsonResponseBodyConverter(Gson gson, TypeAdapter<T> adapter) {
            this.gson = gson;
            this.adapter = adapter;
        }

        @Override
        public T convert(ResponseBody value) throws IOException {
            JsonReader jsonReader = gson.newJsonReader(value.charStream());
            try {
                T result = adapter.read(jsonReader);
                if (jsonReader.peek() != JsonToken.END_DOCUMENT) {
                    throw new JsonIOException("JSON document was not fully consumed.");
                }
                return result;
            } catch (Exception e) {
                //判斷是否被代理了
                if (value.getClass().getDeclaredFields().length > 0
                        && value.getClass().getDeclaredFields()[0].getName().equals("delegate")) {
                    try {
                        //獲取被代理對象
                        Class eRspon = value.getClass();
                        eRspon.getDeclaredField("delegate").setAccessible(true);
                        Field field = eRspon.getDeclaredField("delegate");
                        field.setAccessible(true);
                        Object obj = field.get(value);
                        //判斷代理對象是否為自己定義的類
                        if (obj instanceof MyResponseBody) {
                            //解析失敗情況下會將異常上報服務器
                            String url = ((MyResponseBody) obj).url;

                            CrashReport.postCatchedException(new Exception("解析失斁萆颉:"  + url +
                                    "\n異常如下:" +
                                    "\n" + e.getMessage()));
                        }
                    } catch (Exception ex) {
                        ex.printStackTrace();
                    }
                }
                throw e;
            } finally {
                value.close();
            }
        }
    }

    final class GsonRequestBodyConverter<T> implements Converter<T, RequestBody> {
        private final MediaType MEDIA_TYPE = MediaType.get("application/json; charset=UTF-8");
        private final Charset UTF_8 = Charset.forName("UTF-8");

        private final Gson gson;
        private final TypeAdapter<T> adapter;

        GsonRequestBodyConverter(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());
        }
    }

}

package com.hcb.base.app.http;

import java.nio.charset.Charset;

import androidx.annotation.Nullable;
import okhttp3.MediaType;
import okhttp3.ResponseBody;
import okio.Buffer;
import okio.BufferedSource;
import okio.ByteString;

import static okhttp3.internal.Util.UTF_8;

/**
 * 繼承接口返回對象,添加關聯(lián)接口
 *
 * @author 陳聰 2020-07-20 09:25
 */
public abstract class MyResponseBody extends ResponseBody {
    /** 接口請求鏈接 */
    String url = "";

    /**
     * Returns a new response body that transmits {@code content}. If {@code contentType} is non-null
     * and lacks a charset, this will use UTF-8.
     */
    public static MyResponseBody create(@Nullable MediaType contentType, String content) {
        Charset charset = UTF_8;
        if (contentType != null) {
            charset = contentType.charset();
            if (charset == null) {
                charset = UTF_8;
                contentType = MediaType.parse(contentType + "; charset=utf-8");
            }
        }
        Buffer buffer = new Buffer().writeString(content, charset);
        return create(contentType, buffer.size(), buffer);
    }

    /** Returns a new response body that transmits {@code content}. */
    public static MyResponseBody create(final @Nullable MediaType contentType, byte[] content) {
        Buffer buffer = new Buffer().write(content);
        return create(contentType, content.length, buffer);
    }

    /** Returns a new response body that transmits {@code content}. */
    public static MyResponseBody create(@Nullable MediaType contentType, ByteString content) {
        Buffer buffer = new Buffer().write(content);
        return create(contentType, content.size(), buffer);
    }

    /** Returns a new response body that transmits {@code content}. */
    public static MyResponseBody create(final @Nullable MediaType contentType,
                                        final long contentLength, final BufferedSource content) {
        if (content == null) throw new NullPointerException("source == null");
        return new MyResponseBody() {
            @Override
            public @Nullable
            MediaType contentType() {
                return contentType;
            }

            @Override
            public long contentLength() {
                return contentLength;
            }

            @Override
            public BufferedSource source() {
                return content;
            }
        };
    }
}

最后編輯于
?著作權歸作者所有,轉載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末饺蔑,一起剝皮案震驚了整個濱河市锌介,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌猾警,老刑警劉巖孔祸,帶你破解...
    沈念sama閱讀 218,546評論 6 507
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件玻侥,死亡現(xiàn)場離奇詭異卡骂,居然都是意外死亡,警方通過查閱死者的電腦和手機吓歇,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,224評論 3 395
  • 文/潘曉璐 我一進店門雳窟,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人匣屡,你說我怎么就攤上這事封救。” “怎么了捣作?”我有些...
    開封第一講書人閱讀 164,911評論 0 354
  • 文/不壞的土叔 我叫張陵誉结,是天一觀的道長。 經(jīng)常有香客問我券躁,道長惩坑,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,737評論 1 294
  • 正文 為了忘掉前任也拜,我火速辦了婚禮以舒,結果婚禮上,老公的妹妹穿的比我還像新娘慢哈。我一直安慰自己蔓钟,他們只是感情好,可當我...
    茶點故事閱讀 67,753評論 6 392
  • 文/花漫 我一把揭開白布卵贱。 她就那樣靜靜地躺著滥沫,像睡著了一般。 火紅的嫁衣襯著肌膚如雪键俱。 梳的紋絲不亂的頭發(fā)上兰绣,一...
    開封第一講書人閱讀 51,598評論 1 305
  • 那天,我揣著相機與錄音编振,去河邊找鬼缀辩。 笑死,一個胖子當著我的面吹牛,可吹牛的內(nèi)容都是我干的雌澄。 我是一名探鬼主播斋泄,決...
    沈念sama閱讀 40,338評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼镐牺!你這毒婦竟也來了炫掐?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 39,249評論 0 276
  • 序言:老撾萬榮一對情侶失蹤睬涧,失蹤者是張志新(化名)和其女友劉穎募胃,沒想到半個月后,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體畦浓,經(jīng)...
    沈念sama閱讀 45,696評論 1 314
  • 正文 獨居荒郊野嶺守林人離奇死亡痹束,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,888評論 3 336
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了讶请。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片祷嘶。...
    茶點故事閱讀 40,013評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖夺溢,靈堂內(nèi)的尸體忽然破棺而出论巍,到底是詐尸還是另有隱情,我是刑警寧澤风响,帶...
    沈念sama閱讀 35,731評論 5 346
  • 正文 年R本政府宣布嘉汰,位于F島的核電站,受9級特大地震影響状勤,放射性物質發(fā)生泄漏鞋怀。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 41,348評論 3 330
  • 文/蒙蒙 一持搜、第九天 我趴在偏房一處隱蔽的房頂上張望密似。 院中可真熱鬧,春花似錦葫盼、人聲如沸辛友。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,929評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽废累。三九已至,卻和暖如春脱盲,著一層夾襖步出監(jiān)牢的瞬間邑滨,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,048評論 1 270
  • 我被黑心中介騙來泰國打工钱反, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留掖看,地道東北人匣距。 一個月前我還...
    沈念sama閱讀 48,203評論 3 370
  • 正文 我出身青樓,卻偏偏與公主長得像哎壳,于是被迫代替她去往敵國和親毅待。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 44,960評論 2 355

推薦閱讀更多精彩內(nèi)容