如何在http请求中分别测量发送和接收数据的持续时间

时间:2019-02-15 10:03:24

标签: java http

在使用Java进行HTTP请求期间,我需要分别测量以下时间:

  1. 连接时间
  2. 发送请求时间
  3. 接收响应时间

目前,我只能测量连接时间以及请求和响应时间:

        URL url = new URL("https://stackoverflow.com/");
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setInstanceFollowRedirects(false);
        connection.setConnectTimeout(5000);
        connection.setReadTimeout(5000);
        Instant time1 = Instant.now();
        connection.connect();
        Instant time2 = Instant.now();
        System.out.println(connection.getResponseCode());
        Instant time3 = Instant.now();
        InputStream stream = connection.getInputStream();
        stream.readAllBytes();
        Instant time4 = Instant.now();

        System.out.printf("Connection: %d ms\n", Duration.between(time1, time2).toMillis());
        System.out.printf("Request/Receive Headers : %d ms\n", Duration.between(time2, time3).toMillis());
        System.out.printf("Receive Body : %d ms\n", Duration.between(time3, time4).toMillis());

//输出:

  • 连接:296毫秒
  • 请求/接收标头:156毫秒
  • 接收身体:437毫秒

如何分别计算“请求”时间?

0 个答案:

没有答案