JSON印刷要求体okhttp3中(requestBody)

インターセプタ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();
    }
复制代码

おすすめ

転載: juejin.im/post/5d65237cf265da03c02c121d