如何使用java.net.http.HttpClient记录请求/响应?

时间:2018-11-08 19:43:34

标签: java logging java-9 java-11 java-http-client

在Java 9中实验性引入的HttpClient在Java 11中现已稳定,但不足为奇的是,几乎没有项目实际使用它。文档几乎不存在。

进行HTTP调用时最常见的要求之一是记录请求/响应。您将如何使用HttpClient进行操作,而无需在每次调用中手动记录它?是否有其他所有HTTP客户端提供的拦截器机制?

3 个答案:

答案 0 :(得分:7)

您可以通过在Java命令行上指定$('.APart').each(function(index, element) { $(this).children('.Main').find('.MainClass').each(function (i,e){ console.log($(e).val()) }); $(this).children('.Sub').find('.SubClass').each(function (i,e){ console.log($(e).val()) }); }); 来记录请求和响应。

对于测试/模拟,您可能需要看一下离线测试: JavaDoc

根据要实现的目标,您也可以使用“ DelegatingHttpClient”来拦截和记录请求和响应。

除了Java API文档外,http://hg.openjdk.java.net/jdk/jdk/file/tip/test/jdk/java/net/httpclient/offline/上还有一些高级文档

附加说明:

var validationResults = new List<ValidationResult>(); foreach (var b in obj) { var context = new ValidationContext(b); var isValid = Validator.TryValidateObject(b,context,validationResults); 'do whatever..... } 属性是特定于实现的属性,其值是逗号分隔的列表,可以在Java命令行上将其配置为具有以下值的诊断/调试目的:

-Djdk.httpclient.HttpClient.log=requests

答案 1 :(得分:4)

如果我们查看jdk.internal.net.http.common.DebugLogger源代码,我们会看到一些使用System.Logger的记录器,而这些记录器将依次使用System.LoggerFinder选择记录器框架。 JUL是默认选择。记录器名称为:

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

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

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)
...

答案 2 :(得分:0)

在我们这方面,我们发现-Djdk.internal.httpclient.debug提供的日志不够可读。我们想到的解决方案是用装饰器包装HttpClient,该装饰器将能够拦截调用并提供日志记录。这里看起来是这样的(不仅应该对send方法而且应该对sendAsync方法进行操作):

public class HttpClientLoggingDecorator extends HttpClient {

  private static final Logger logger = Logger.getLogger(HttpClientLoggingDecorator.class.getName());

  private final HttpClient client;

  ...

  @Override
  public <T> HttpResponse<T> send(HttpRequest req, HttpResponse.BodyHandler<T> responseBodyHandler)
    throws IOException,
      InterruptedException
  {
    subscribeLoggerToRequest(req);

    HttpResponse<T> response = client.send(req, responseBodyHandler);

    logResponse(response);
    return response;
  }

  private void subscribeLoggerToRequest(HttpRequest req) {
    // define a consumer for how you want to log
    // Consumer<String> bodyConsumer = ...;
    if (req.bodyPublisher().isPresent()) {
      req.bodyPublisher()
              .ifPresent(bodyPublisher -> bodyPublisher.subscribe(new HttpBodySubscriber(bodyConsumer)));
    } else {
      bodyConsumer.accept(NO_REQUEST_BODY);
    }
  }

  private <T> void logResponse(HttpResponse<T> response) {
    // String responseLog = ...;
    logger.info(responseLog);
  }

}

这是HttpBodySubscriber

public class HttpBodySubscriber implements Flow.Subscriber<ByteBuffer> {

  private static final long UNBOUNDED = Long.MAX_VALUE;

  private final Consumer<String> logger;

  public HttpBodySubscriber(Consumer<String> logger) {
    this.logger = logger;
  }

  @Override
  public void onSubscribe(Flow.Subscription subscription) {
    subscription.request(UNBOUNDED);
  }

  @Override
  public void onNext(ByteBuffer item) {
    logger.accept(new String(item.array(), StandardCharsets.UTF_8));
  }

  @Override
  public void onError(Throwable throwable) {
  }

  @Override
  public void onComplete() {
  }

}