在java中Ping url并获取状态

在java中Ping url并获取状态,java,Java,这就是我目前所尝试的。 要ping URL,请执行以下操作: public static boolean pingUrl(final String address) { try { final URL url = new URL("http://" + address); final HttpURLConnection urlConn = (HttpURLConnection) url.openConnection(); urlConn.setConnectTimeout(100

这就是我目前所尝试的。

要ping URL,请执行以下操作:

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;
}
要ping URL,请执行以下操作:

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;
}

首先,请把代码贴出来。第二,如果您使用URLConnection连接到URL,您可能不需要ping/wget。可能重复:可能重复第一个的可能重复,请发布代码。第二,如果使用URLConnection连接URL,可能不需要ping/wget
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;
}