title: Correct way to get a Server Response Time from a URL in java?
body: <p>Correct way to get a Server Response Time from a URL in java?</p>
  
  <ol>
  <li>i have x2 code examples, but not sure whether any of the following are correct?</li>
  </ol>
  
  <p><strong>Code Example1:</strong></p>
  
  <pre><code>    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) {
      }
  }
  </code></pre>
  
  <p><strong>Code Example2:</strong></p>
  
  <pre><code>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/");
  }
  </code></pre>
  
  <p><a href="https://i.stack.imgur.com/DsnGi.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/DsnGi.jpg" alt="enter image description here"></a></p>