在okhttp3中打印JSON請求體(RequestBody)

在okhttp3中添加攔截器,打印請求的網絡信息是一個通用的需求。下面是打印JSON請求體的方法。java

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();
    }
複製代碼
相關文章
相關標籤/搜索