如何使用 java.net.http.HttpClient 记录请求/响应? [英] How to log request/response using java.net.http.HttpClient?

查看:60
本文介绍了如何使用 java.net.http.HttpClient 记录请求/响应?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

HttpClient 现在在 Java 11 中是稳定的,但毫不奇怪,似乎很少有项目实际使用它.文档几乎不存在.

The HttpClient introduced experimentally in Java 9 is now stable in Java 11, but not surprisingly, very few projects seem to actually use it. Documentation is almost non-existing.

进行 HTTP 调用时最常见的问题之一是记录请求/响应.您将如何使用 HttpClient 做到这一点,当然,不用在每次调用时手动记录它?是否有类似所有其他 HTTP 客户端提供的拦截器机制?

One of the most commons asks while making a HTTP call is logging of request/response. How would you do that using the HttpClient, without of course, logging it manually in every single call? Is there an interceptor mechanism like that offered by all other HTTP clients?

推荐答案

如果我们查看 jdk.internal.net.http.common.DebugLogger 源代码,我们可以看到一些使用 System.Logger,反过来将使用System.LoggerFinder 选择记录器框架.JUL 是默认选择.记录器名称是:

If we look at jdk.internal.net.http.common.DebugLogger source code we can see a few loggers using System.Logger, which in turn will useSystem.LoggerFinder to select the logger framework. JUL is the default choice. The logger names are:

  • jdk.internal.httpclient.debug
  • jdk.internal.httpclient.websocket.debug
  • jdk.internal.httpclient.hpack.debug

可以通过将它们设置为系统属性来启用它们.例如使用 -Djdk.internal.httpclient.debug=true 运行将产生:

They can be enabled by setting them as a system property. For example running with -Djdk.internal.httpclient.debug=true will produce:

DEBUG: [main] [147ms] HttpClientImpl(1) proxySelector is sun.net.spi.DefaultProxySelector@6dde5c8c (user-supplied=false)
DEBUG: [main] [183ms] HttpClientImpl(1) ClientImpl (async) send https://http2.github.io/ GET
DEBUG: [main] [189ms] Exchange establishing exchange for https://http2.github.io/ GET,
     proxy=null
DEBUG: [main] [227ms] PlainHttpConnection(?) Initial receive buffer size is: 43690
DEBUG: [main] [237ms] PlainHttpConnection(SocketTube(1)) registering connect event
DEBUG: [HttpClient-1-SelectorManager] [239ms] SelectorAttachment Registering jdk.internal.net.http.PlainHttpConnection$ConnectEvent@354bf356 for 8 (true)
...

这篇关于如何使用 java.net.http.HttpClient 记录请求/响应?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆