java ping url并在java中获取状态

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6381306/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 15:40:24  来源:igfitidea点击:

Ping url and get status in java

java

提问by Linda

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

This is what i have tried at present.

这是我目前尝试过的。

回答by gtiwari333

Ping URL from JAVA Code

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

回答by Yousha Aleayoub

To ping a URL:

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