在okhttp3中打印JSON请求体(RequestBody)

5,351 阅读1分钟

在okhttp3中添加拦截器,打印请求的网络信息是一个通用的需求。下面是打印JSON请求体的方法。

private static String bodyToString(final Request request){

    try {
        final Request copy = request.newBuilder().build();
        final Buffer buffer = new Buffer();
        copy.body().writeTo(buffer);
        return buffer.readUtf8();
    } catch (final IOException e) {
        return "error";
    }
}

拦截器当中使用

    @Override
    public okhttp3.Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        long startTime = System.currentTimeMillis();
        okhttp3.Response response = chain.proceed(chain.request());
        long endTime = System.currentTimeMillis();
        long duration=endTime-startTime;
        okhttp3.MediaType mediaType = response.body().contentType();
        String content = response.body().string();
        LoggerUtil.info("----------Start----------------");
        LoggerUtil.info("| "+request.toString());
        String method=request.method();
        if("POST".equals(method)){
            LoggerUtil.info("request:\n" + this.bodyToString(request));
        }
        LoggerUtil.info("| Response:" + content);
        LoggerUtil.info("----------End:"+duration+"毫秒----------");
        return response.newBuilder()
                .body(okhttp3.ResponseBody.create(mediaType, content))
                .build();
    }