Java 如何通过 Socket 找到 HTTP 请求的响应时间

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/68999/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 07:54:32  来源:igfitidea点击:

How can I find the response time of a HTTP request through a Socket

javahttp

提问by Martin Andersson

I'm using a Java socket, connected to a server. If I send a HEADER http request, how can I measure the response time from the server? Must I use a provided java timer, or is there an easier way?

我正在使用连接到服务器的 Java 套接字。如果我发送 HEADER http 请求,如何测量服务器的响应时间?我必须使用提供的 java 计时器,还是有更简单的方法?

I'm looking for a short answer, I don't want to use other protocols etc. Obviously do I neither want to have a solution that ties my application to a specific OS. Please people, IN-CODE solutions only.

我正在寻找一个简短的答案,我不想使用其他协议等。显然我也不希望有一个将我的应用程序绑定到特定操作系统的解决方案。请人们,仅限代码中的解决方案。

采纳答案by Dave L.

I would say it depends on what exact interval you are trying measure, the amount of time from the last byte of the request that you send until the first byte of the response that you receive? Or until the entire response is received? Or are you trying to measure the server-side time only?

我会说这取决于您尝试测量的确切间隔,从您发送的请求的最后一个字节到您收到的响应的第一个字节的时间?或者直到收到整个响应?还是您只想测量服务器端时间?

If you're trying to measure the server side processing time only, you're going to have a difficult time factoring out the amount of time spent in network transit for your request to arrive and the response to return. Otherwise, since you're managing the request yourself through a Socket, you can measure the elapsed time between any two moments by checking the System timer and computing the difference. For example:

如果您只想测量服务器端的处理时间,那么您将很难计算出网络传输所花费的时间来让您的请求到达和返回的响应。否则,由于您是通过 Socket 自己管理请求,您可以通过检查系统计时器并计算差异来测量任意两个时刻之间经过的时间。例如:

public void sendHttpRequest(byte[] requestData, Socket connection) {
    long startTime = System.nanoTime();
    writeYourRequestData(connection.getOutputStream(), requestData);
    byte[] responseData = readYourResponseData(connection.getInputStream());
    long elapsedTime = System.nanoTime() - startTime;
    System.out.println("Total elapsed http request/response time in nanoseconds: " + elapsedTime);
}

This code would measure the time from when you begin writing out your request to when you finish receiving the response, and print the result (assuming you have your specific read/write methods implemented).

此代码将测量从您开始写出请求到完成接收响应的时间,并打印结果(假设您实现了特定的读/写方法)。

回答by hoyhoy

You can use time and curl and time on the command-line. The -I argument for curl instructs it to only request the header.

您可以在命令行上使用 time 和 curl 和 time。curl 的 -I 参数指示它仅请求标头。

time curl -I 'http://server:3000'

回答by Dave Cheney

Something like this might do the trick

像这样的事情可能会奏效

import java.io.IOException;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.URIException;
import org.apache.commons.httpclient.methods.HeadMethod;
import org.apache.commons.lang.time.StopWatch;
//import org.apache.commons.lang3.time.StopWatch

public class Main {

    public static void main(String[] args) throws URIException {
        StopWatch watch = new StopWatch();
        HttpClient client = new HttpClient();
        HttpMethod method = new HeadMethod("http://stackoverflow.com/");

        try {
            watch.start();
            client.executeMethod(method);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            watch.stop();
        }

        System.out.println(String.format("%s %s %d: %s", method.getName(), method.getURI(), method.getStatusCode(), watch.toString()));

    }
}
HEAD http://stackoverflow.com/ 200: 0:00:00.404

回答by Kevin Day

Maybe I'm missing something, but why don't you just use:

也许我错过了一些东西,但你为什么不直接使用:

// open your connection
long start = System.currentTimeMillis();
// send request, wait for response (the simple socket calls are all blocking)
long end = System.currentTimeMillis();
System.out.println("Round trip response time = " + (end-start) + " millis");

回答by Adisesha

Use AOP to intercept calls to the socket and measure the response time.

使用 AOP 拦截对套接字的调用并测量响应时间。

回答by A B

curl -s -w "%{time_total}\n" -o /dev/null http://server:3000

curl -s -w "%{time_total}\n" -o /dev/null http://server:3000

回答by Sudabe-Neirizi

@Aspect
@Profile("performance")
@Component
public class MethodsExecutionPerformance {
    private final Logger logger = LoggerFactory.getLogger(getClass());

    @Pointcut("execution(* it.test.microservice.myService.service.*.*(..))")
    public void serviceMethods() {
    }

    @Around("serviceMethods()")
    public Object monitorPerformance(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        StopWatch stopWatch = new StopWatch(getClass().getName());
        stopWatch.start();
        Object output = proceedingJoinPoint.proceed();
        stopWatch.stop();
        logger.info("Method execution time\n{}", stopWatch.prettyPrint());
        return output;
    }
}

In this way, you can calculate the real response time of your service independent of network speed.

通过这种方式,您可以独立于网络速度计算服务的实际响应时间。