有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

Ping url并获取java中的状态

         URLPing urlPing = new URLPing();
         PingResponse pingResponse = urlPing.ping(URLName);
         if(pingResponse.getResponseCode() == 200){
                response = true;
         }
         else{
                response=false;
         }

这就是我目前所尝试的


共 (2) 个答案

  1. # 1 楼答案

    Ping URL from JAVA Code

    public static boolean pingUrl(final String address) {
     try {
      final URL url = new URL("http://" + address);
      final HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
      urlConn.setConnectTimeout(1000 * 10); // mTimeout is in seconds
      final long startTime = System.currentTimeMillis();
      urlConn.connect();
      final long endTime = System.currentTimeMillis();
      if (urlConn.getResponseCode() == HttpURLConnection.HTTP_OK) {
       System.out.println("Time (ms) : " + (endTime - startTime));
       System.out.println("Ping to "+address +" was success");
       return true;
      }
     } catch (final MalformedURLException e1) {
      e1.printStackTrace();
     } catch (final IOException e) {
      e.printStackTrace();
     }
     return false;
    }
    
  2. # 2 楼答案

    要ping一个URL:

    public static boolean exists()
    {
       try
       {
          return (Runtime.getRuntime().exec("/system/bin/ping -c 1 google.com").waitFor() == 0);
       }
       catch (IOException | InterruptedException exception)
       {
          exception.printStackTrace();
          // Handler
       }
    
       return false;
    }