2014-09-12 63 views
16

我有一个URL的形式如何快速检查URL服务器可用

http://www.mywebsite.com/util/conv?a=1&from=%s&to=%s 

而且要检查它是否可用。

如果我尝试用浏览器打开这些链接,链接将重定向到一个错误的请求页面,但通过代码我可以获取我需要的数据。

在HTTP请求过程中使用try-catch块非常慢,所以我想知道如何ping一个类似的地址来检查它的服务器是否处于活动状态。


我已经试过

boolean reachable = InetAddress.getByName(myLink).isReachable(6000); 

但总是返回false

我也曾尝试

public static boolean exists(String URLName) { 

    try { 
     HttpURLConnection.setFollowRedirects(false); 
     HttpURLConnection con = (HttpURLConnection) new URL(URLName).openConnection(); 
     con.setConnectTimeout(1000); 
     con.setReadTimeout(1000); 
     con.setRequestMethod("HEAD"); 
     return (con.getResponseCode() == HttpURLConnection.HTTP_OK); 
    } catch (Exception e) { 
     e.printStackTrace(); 
     return false; 
    } 
} 

返回在过程结束时正确的值,如果服务器不可用有点太慢了。

编辑

我已经明白了是缓慢的原因

一)如果服务器返回了一些数据,但中断请求之前完成请求超时被忽略,并卡住,直到返回一个Exception这导致执行到达catch块,这是这种方法缓慢的原因,但我还没有找到有效的解决方案来避免这种情况。

b)如果我启动android设备并在没有连接的情况下打开应用程序,则错误值将被正确返回,如果应用程序在互联网连接处于活动状态并且设备失去其Internet连接时打开,则会发生与情况A相同的情况(也如果我试图终止并重新启动应用程序...我不知道为什么,我想这东西仍然缓存)

所有这些似乎与事实Java URLConnection不提供故障安全超时读取。看看this link的示例,我已经看到使用线程以某种方式中断连接,但如果我简单地添加new Thread(new InterruptThread(Thread.currentThread(), con)).start();这一行,就像示例中没有任何更改。

+1

尝试使用getResponseMessage()或getResponseCode() – KOTIOS 2014-09-12 09:59:20

+0

错误的请求意味着您的URL无效,但并非服务器不可用 – 2014-09-12 11:03:46

+0

@mtetno您能否给我更多详细信息用户回答了类似的问题,例外的相关尝试catch块 – AndreaF 2014-09-12 15:59:59

回答

2
public static boolean exists(String URLName) { 

     try { 
      HttpURLConnection.setFollowRedirects(false); 
      // note : you may also need 
      // HttpURLConnection.setInstanceFollowRedirects(false) 
      HttpURLConnection con = (HttpURLConnection) new URL(URLName) 
      .openConnection(); 
      con.setRequestMethod("HEAD"); 
      return (con.getResponseCode() == HttpURLConnection.HTTP_OK); 
     } catch (Exception e) { 
      e.printStackTrace(); 
      return false; 
     } 
    } 
+0

此代码的作品,但速度一样慢,等待尝试捕获块 – AndreaF 2014-09-12 15:58:38

0

您是否尝试过使用原始套接字?

应该运行得更快,因为它是在下层

static boolean exists(String serverUrl) { 

    final Socket socket; 

    try { 
     URL url = new URL(serverUrl); 
     socket = new Socket(url.getHost(), url.getPort()); 
    } catch (IOException e) { 
     return false; 
    } 

    try { 
     socket.close(); 
    } catch (IOException e) { 
     // will never happen, it's thread-safe 
    } 

    return true; 
} 
+0

的异常与此代码应用程序崩溃并获取端口超出范围异常 – AndreaF 2014-09-18 16:43:07

14
static public boolean isServerReachable(Context context) { 
    ConnectivityManager connMan = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); 
    NetworkInfo netInfo = connMan.getActiveNetworkInfo(); 
    if (netInfo != null && netInfo.isConnected()) { 
     try { 
      URL urlServer = new URL("your server url"); 
      HttpURLConnection urlConn = (HttpURLConnection) urlServer.openConnection(); 
      urlConn.setConnectTimeout(3000); //<- 3Seconds Timeout 
      urlConn.connect(); 
      if (urlConn.getResponseCode() == 200) { 
       return true; 
      } else { 
       return false; 
      } 
     } catch (MalformedURLException e1) { 
      return false; 
     } catch (IOException e) { 
      return false; 
     } 
    } 
    return false; 
} 

或使用运行时:

Runtime runtime = Runtime.getRuntime(); 
Process proc = runtime.exec("ping www.serverURL.com"); //<- Try ping -c 1 www.serverURL.com 
int mPingResult = proc .waitFor(); 
if(mPingResult == 0){ 
    return true; 
}else{ 
    return false; 
} 

你可以试试isReachable()但有一个bug filed for itthis comment says that isReachable() requires root permission

try { 
    InetAddress.getByName("your server url").isReachable(2000); //Replace with your name 
    return true; 
} catch (Exception e) 
{ 
    return false; 
} 
+0

第一个示例具有相同的问题,我已发布的代码(工作但服务器没有给出响应时很慢),第二个示例返回总是假的 – AndreaF 2014-09-18 19:15:50

+0

我编辑了我的答案,也尝试'ping -c 1 www.serverURL.com' – 2014-09-19 06:06:32

+0

我在ping后添加了-1 c,但返回始终为false,尽管第一个方法在同一个链接上返回正确为true – AndreaF 2014-09-19 17:16:26

0

正如'eridal'所提到的那样,应该更快,打开插座;但是,它只会告诉你一台服务器正在监听主机和端口,但是可以肯定的是,你需要编写HTTP或者一个错误的请求(垃圾),你应该得到HTTP/1.1 400错误请求。通过读取返回的第一行,如果它包含HTTP,那么您确定该服务器是一个HTTP服务器。这样你就可以确定服务器和HTTP服务器都可用。

这是对eridal的上述回答的扩展。

-1

上个月我有类似的问题,有人帮我一个可选的例子。我想建议你一样

public boolean isServerReachable() 
    // To check if server is reachable 
    { 
     try { 
      InetAddress.getByName("google.com").isReachable(3000); //Replace with your name 
      return true; 
     } catch (Exception e) { 
      return false; 
     } 
    } 

如果返回true,则表示您的url服务器可用,否则当前不可用。

+0

或者您可以检查 http://stackoverflow.com/questions/ 25541940/android-check-condition-for-server-down – 2014-09-19 05:56:06

+0

正如我在我的问题中所说的,此代码rteturns总是虚假的,与我的链接 – AndreaF 2014-09-20 11:51:14

+0

您的链接会将您带到链接“http://website.1and1.com/#top “所以只能使用** website.1and1.com **。它返回true – 2014-09-22 07:39:39

-1
if (android.os.Build.VERSION.SDK_INT > 9) { 
          StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder() 
            .permitAll().build(); 

          StrictMode.setThreadPolicy(policy); 
         } 
         try { 
          URL diachi = new URL("http://example.com"); 
          HttpURLConnection huc = (HttpURLConnection) diachi.openConnection(); 
          huc.setRequestMethod("HEAD"); 
          int responseCode = huc.getResponseCode(); 

          if (responseCode != 404) { 
           //URL Exist 

          } else { 
           //URL not Exist 
          } 
         } catch (MalformedURLException e) { 
          e.printStackTrace(); 
         } catch (IOException e) { 
          e.printStackTrace(); 
         } 
0

试试这个代码

public boolean isServerAlive() 
    // To check if server is reachable 
{ 
    try { 
     InetAddress.getByName("google.com").isReachable(3000); //Replace with your name 
     return true; 
    } catch (Exception e) { 
     return false; 
    } 
} 
0

下面的代码一直等待,直到网页可用:

public void waitForWebavailability() throws Exception { 
     boolean success = false; 
     long waitTime = 0; 
     while (!success) { 
      try { 
       waitTest(30000); 
       waitTime += 30000; 
       if (waitTime > 600000) { 

        System.out.println("Web page is not available"); 
       } 
       webDriver.get("http://www.google.com"); 
       if (webDriver.getTitle().toLowerCase().contains("sometitle")) { 
        success = true; 
       } 
      } catch (Exception e) { 
       success = false; 
      } 

     } 

    } 

// Code related to waittest 

public void waitTest(long millis) throws Exception { 
     try { 
      Thread.sleep(millis); 
     } catch (InterruptedException e) { 
      throw new Exception(e); 
     } 
    } 
0

here笔者提出这样的:

public boolean isOnline() { 
    Runtime runtime = Runtime.getRuntime(); 
    try { 
     Process ipProcess = runtime.exec("/system/bin/ping -c 1 8.8.8.8"); 
     int  exitValue = ipProcess.waitFor(); 
     return (exitValue == 0); 
    } catch (IOException | InterruptedException e) { e.printStackTrace(); } 
    return false; 
} 

我不能直接ping我自己的页面,我想要求吗?当然!如果您想区分“可用的互联网连接”和您自己的服务器可达,您甚至可以同时检查这两个选项。

阅读链接。它看起来很不错

编辑:我在使用它的EXP ,它的速度比不上这个方法:

public boolean isOnline() { 
    NetworkInfo netInfo = connectivityManager.getActiveNetworkInfo(); 
    return netInfo != null && netInfo.isConnectedOrConnecting(); 
} 

他们有点不同,但在功能只是检查互联网的连接由于连接变量,第一种方法可能会变慢。