从java中的URL获取服务器响应时间的正确方法?

时间:2017-03-17 10:09:36

标签: java selenium server webdriver

从java中的URL获取服务器响应时间的正确方法?

  1. 我有x2代码示例,但不确定以下任何一项是否正确?
  2. 代码示例1:

        public static void getResponseCode2(String urlString) throws MalformedURLException, IOException {
        try {
            URL url = new URL(urlString);
            HttpURLConnection huc = (HttpURLConnection) url.openConnection();
            huc.setRequestMethod("GET");
            StopWatch pageLoad = new StopWatch();
            pageLoad.start();
            huc.connect();
            pageLoad.stop();
            long pageLoadTime_ms = pageLoad.getTime();
            long pageLoadTime_Seconds = pageLoadTime_ms / 1000;
            long pageLoadTime_SecondsRemainder = (pageLoadTime_ms % 1000);
            System.out.println("Total Page Load Time: " + pageLoadTime_ms + " milliseconds");
            System.out.println("Total Page Load Time: " + "Seconds:" + pageLoadTime_Seconds + ", Remainder:"+ pageLoadTime_SecondsRemainder);
            System.out.println("Status Code: " + huc.getResponseCode());
        } catch (IOException e) {
        }
    }
    

    代码示例2:

    public static void pingURL(String url, int timeout) {
            url = url.replaceFirst("^https", "http");
            try {
                StopWatch pageLoad = new StopWatch();
                pageLoad.start();
                HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
                connection.setConnectTimeout(timeout);
                connection.setReadTimeout(timeout);
                connection.setRequestMethod("HEAD");
                pageLoad.stop();
                long pageLoadTime_ms = pageLoad.getTime();
                long pageLoadTime_Seconds = pageLoadTime_ms / 1000;
                long pageLoadTime_SecondsRemainder = (pageLoadTime_ms % 1000);
                System.out.println("Total Page Load Time: " + pageLoadTime_ms + " milliseconds");
                System.out.println("Total Page Load Time: " + "Seconds:" + pageLoadTime_Seconds + ", Remainder:"+ pageLoadTime_SecondsRemainder);
            } catch (IOException exception) {
            }
    
    
        public static void main(String[] args) throws MalformedURLException, IOException {
        pingURL("https://www.buyagift.co.uk/", 30);
        getResponseCode2("https://www.buyagift.co.uk/");
    }
    

    enter image description here

0 个答案:

没有答案