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

前端 未结 7 1526
猫巷女王i
猫巷女王i 2021-02-07 04:13

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 t

7条回答
  •  清歌不尽
    2021-02-07 04:16

    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
    

提交回复
热议问题