java – 如何快速检查URL服务器是否可用

前端之家收集整理的这篇文章主要介绍了java – 如何快速检查URL服务器是否可用前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个表单的URL
  1. http://www.mywebsite.com/util/conv?a=1&from=%s&to=%s

并且想检查它是否可用.

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

在HTTP请求过程中使用try-catch块是相当缓慢的,所以我想知道如何ping一个类似的地址来检查它的服务器是否活动.

我努力了

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

但返回总是假的.

我也试过

  1. public static boolean exists(String URLName) {
  2.  
  3. try {
  4. HttpURLConnection.setFollowRedirects(false);
  5. HttpURLConnection con = (HttpURLConnection) new URL(URLName).openConnection();
  6. con.setConnectTimeout(1000);
  7. con.setReadTimeout(1000);
  8. con.setRequestMethod("HEAD");
  9. return (con.getResponseCode() == HttpURLConnection.HTTP_OK);
  10. } catch (Exception e) {
  11. e.printStackTrace();
  12. return false;
  13. }
  14. }

这将在进程结束时返回正确的值,如果服务器不可用,则位太慢.

编辑

我已经明白缓慢的原因是什么

a)如果服务器返回一些数据,但在完成请求之前中断请求,超时被忽略并被卡住,直到返回一个导致执行到达catch块的异常,这是造成此方法缓慢的原因,而且我仍然避开没有找到一个有效的解决方案来避免这种情况.

b)如果我启动Android设备并打开没有连接的应用程序,则false值将正确返回,如果应用程序打开,Internet连接处于活动状态,并且设备丢失其Internet连接发生在与A情况相同的情况(也如果我尝试终止并重新启动应用程序…我不知道为什么,我想有些东西仍然缓存)

所有这一切似乎与Java URLConnection在读取时不提供故障安全超时的事实有关.看看this link的样本,我看到使用线程以某种方式中断连接,但如果我添加一行新线程(新的InterruptThread(Thread.currentThread(),con)).start();像在样品中没有变化.

解决方法

  1. static public boolean isServerReachable(Context context) {
  2. ConnectivityManager connMan = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
  3. NetworkInfo netInfo = connMan.getActiveNetworkInfo();
  4. if (netInfo != null && netInfo.isConnected()) {
  5. try {
  6. URL urlServer = new URL("your server url");
  7. HttpURLConnection urlConn = (HttpURLConnection) urlServer.openConnection();
  8. urlConn.setConnectTimeout(3000); //<- 3Seconds Timeout
  9. urlConn.connect();
  10. if (urlConn.getResponseCode() == 200) {
  11. return true;
  12. } else {
  13. return false;
  14. }
  15. } catch (MalformedURLException e1) {
  16. return false;
  17. } catch (IOException e) {
  18. return false;
  19. }
  20. }
  21. return false;
  22. }

或使用运行时:

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

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

  1. try {
  2. InetAddress.getByName("your server url").isReachable(2000); //Replace with your name
  3. return true;
  4. } catch (Exception e)
  5. {
  6. return false;
  7. }

猜你在找的Java相关文章