Adding an interceptor to OKHttp3 to print the requested network information is a common requirement. Here is how to print the body of the JSON request.

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"; }}Copy the code

Used in interceptors

    @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+"Ms -- -- -- -- -- -- -- -- -- --");
        return response.newBuilder()
                .body(okhttp3.ResponseBody.create(mediaType, content))
                .build();
    }
Copy the code