Android 获取Okhttp网络日志

96 阅读1分钟

由于ResponseBody内的bytes()、string()方法调用了closeQuietly方法,此方法会将ResponseBody内的数据源清除,所以仅获取一次内容。

解决方案:

@Nullable
public static String readResponseString(@Nullable ResponseBody body) {
    String bodyString = null;
    if (body != null) {
        try {
            BufferedSource source = body.source();
            source.request(Long.MAX_VALUE); // Buffer the entire body.
            Buffer buffer = source.getBuffer();
            Charset charset = checkCharset(body.contentType());
            bodyString = buffer.clone().readString(charset);
        } catch (IOException e) {
            //
        }
    }
    return bodyString;
}

private static final Charset defCharset = StandardCharsets.UTF_8;

@NonNull
public static Charset checkCharset(@Nullable MediaType type) {
    if (type == null) {
        return defCharset;
    }
    Charset charset = type.charset(defCharset);
    if (charset == null) {
        charset = defCharset;
    }
    return charset;
}