okhttp添加拦截器Interceptor

现在Android的的网络请求一般都是使用okhttp,我们在调试接口的时候会在控制台查看接口的数据,那么怎样将请求的信息打印出来呢?事实上,okhttp已经考虑到这种情况了,我们只需要添加拦截器就好了。本来想在网上找个的,结果发现坑好多,很多都不全而且还容易报错,就自己写了一个,分享给大家。

过程就不多说了,直接贴代码

//Log拦截器代码
public class LogInterceptor implements Interceptor {
    private final static String TAG = \"okhttp\";
    private static final Charset UTF8 = Charset.forName("UTF-8");

    @Override
    public Response intercept(Chain chain) throws IOException {

        //log 信息
        StringBuilder builder = new StringBuilder();
        Request request = chain.request();

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

        Connection connection = chain.connection();
        Protocol protocol = connection != null ? connection.protocol() : Protocol.HTTP_1_1;

        String requestStartMessage = "请求方式 ----> " + request.method() + "\n请求地址: "
                + request.url() + "\nHttp 版本:" + protocol;

        builder.append(requestStartMessage);

        if (hasRequestBody) {
            if (requestBody.contentType() != null) {
                builder.append("\n请求头 ----> Content-Type: " + requestBody.contentType());
            }
        }
        builder.append("\n请求参数 ----> ");
        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)) {
                builder.append(name + ": " + headers.value(i));
            }
        }

        if (!hasRequestBody) {
            builder.append("\n请求结束 --> END " + request.method());
        } else if (bodyEncoded(request.headers())) {
            builder.append("\n请求结束 --> 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);
            }

            if (isPlaintext(buffer)) {
                builder.append(buffer.readString(charset));
                builder.append("\n请求结束 --> END " + request.method()
                        + " (" + requestBody.contentLength() + "-byte body)");
            } else {
                builder.append("\n请求结束 --> END " + request.method() + " (binary "
                        + requestBody.contentLength() + "-byte body omitted)");
            }
        }

        long startNs = System.nanoTime();
        Response response;
        try {
            response = chain.proceed(request);
        } catch (Exception e) {
            builder.append("\n请求出错 ----> " + e.getMessage());
            LogUtils.d(TAG, "请求信息如下:\n" + builder);
            throw e;
        }
        long tookMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNs);

        ResponseBody responseBody = response.body();
        Headers responseHeaders = response.request().headers();
        builder.append("\n请求头 ----> \n" + responseHeaders.toString());
        if (requestBody != null) {
            long contentLength = responseBody.contentLength();
            builder.append("请求code ----> " + response.code() + " 用时:(" + tookMs + "ms)");

            BufferedSource source = responseBody.source();
            source.request(Long.MAX_VALUE); // Buffer the entire body.
            Buffer buffer = source.buffer();

            Charset charset = UTF8;
            MediaType contentType = responseBody.contentType();
            if (contentType != null) {
                try {
                    charset = contentType.charset(UTF8);
                } catch (UnsupportedCharsetException e) {
                    builder.append("\nCouldn't decode the response body; charset is likely malformed.");
                    builder.append("\n<-- END HTTP");

                    return response;
                }
            }

            if (!isPlaintext(buffer)) {
                builder.append("\n<-- END HTTP (binary " + buffer.size() + "-byte body omitted)");
                return response;
            }

            if (contentLength != 0) {
                builder.append("\n返回数据 ---->");
                builder.append("\n" + buffer.clone().readString(charset));
            }
            builder.append("\n<-- 请求结束 END HTTP (" + buffer.size() + "-byte body)");
        }


        LogUtils.d(TAG, "请求信息如下:\n" + builder);
        return response;
    }

    /**
     * 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.
     */
    private boolean isPlaintext(Buffer buffer) throws EOFException {
        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 boolean bodyEncoded(Headers headers) {
        String contentEncoding = headers.get("Content-Encoding");
        return contentEncoding != null && !contentEncoding.equalsIgnoreCase("identity");
    }}

如下图所示:
okhttp请求信息

下载资源地址:LogInterceptor

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值