如何快速检查URL服务器可用 [英] How to quickly check if URL server is available

查看:472
本文介绍了如何快速检查URL服务器可用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有格式的URL

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

和要检查是否可用。

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

使用一个HTTP请求的程序一个try-catch块pretty的慢,所以我想知道我怎么可以ping通类似的地址,以检查它的服务器被激活。


我已经试过

 布尔可达= InetAddress.getByName(myLink的).isReachable(6000);
 

但回报总是

我也尝试

 公共静态布尔存在(字符串URLName){

    尝试 {
        HttpURLConnection.setFollowRedirects(假);
        HttpURLConnection的CON =(HttpURLConnection类)新的URL(URLName).openConnection();
        con.setConnectTimeout(1000);
        con.setReadTimeout(1000);
        con.setRequestMethod(头);
        返程(con.getResponse code()== HttpURLConnection.HTTP_OK);
    }赶上(例外五){
        e.printStackTrace();
        返回false;
    }
}
 

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

修改

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

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

二)如果我开始Android设备,并打开App没有连接,假值正确返回,如果应用程序打开互联网连接有源和设备失去了网络连接发生的情况下同样的事情(同样,如果我尝试终止并重新启动应用程序...我不知道为什么,我想的东西在缓存)

这一切似乎与事实的Java URLConnection的不提供无故障安全超时上读取。在研究样本在此链接我有可见,使用一个线程中断以某种方式连接,但如果我只是添加了一行新主题(新InterruptThread(Thread.currentThread(),CON))启动(); 喜欢在什么样的变化。

解决方案

 的静态公共布尔isServerReachable(上下文的背景下){
    ConnectivityManager康曼=(ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
    的NetworkInfo的NetInfo = connMan.getActiveNetworkInfo();
    如果(NetInfo的= NULL和放大器;!&安培; netInfo.isConnected()){
        尝试 {
            网址URL服务器=新的URL(服务器URL);
            HttpURLConnection的urlConn =(HttpURLConnection类)urlServer.openConnection();
            urlConn.setConnectTimeout(3000); //<  -  3秒超时
            urlConn.connect();
            如果(urlConn.getResponse code()== 200){
                返回true;
            } 其他 {
                返回false;
            }
        }赶上(MalformedURLException的E1){
            返回false;
        }赶上(IOException异常E){
            返回false;
        }
    }
    返回false;
}
 

或使用运行时:

 运行运行时间=调用Runtime.getRuntime();
流程PROC =的Runtime.exec(平www.serverURL.com); //<  - 尝试平-C 1 www.serverURL.com
INT mPingResult = PROC .waitFor();
如果(mPingResult == 0){
    返回true;
}其他{
    返回false;
}
 

您可以尝试 isReachable()但有一个的错误申请它和<一href="http://stackoverflow.com/questions/4779367/problem-with-isreachable-in-inetaddress-class#comment5308364_4779367">this评论说,isReachable()需要root权限:

 尝试{
    InetAddress.getByName(服务器URL)isReachable(2000年)。 //您的姓名替换
    返回true;
}赶上(例外五)
{
    返回false;
}
 

I have a URL in the form

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

And want to check if it is available.

The links redirect me on a bad request page if I try to open these with a browser, however via code I can get the data that I need.

Using a try-catch block on a HTTP request procedure is pretty slow, so I'm wondering how I could ping a similar address to check if its server is active.


I have tried

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

But returns always false.

I have also tried

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

That returns the correct value at the end of the process, bit is too slow if server is not available.

EDIT

I have understood what is the cause of slowness

a) if server returns some data but interrupts the request before complete the request the timeout is ignored and stuck until returns an Exception that lead the execution to reach the catch block, this is the cause of the slowness of this method, and still I haven't found a valid solution to avoid this.

b) If I start the android device and open the App without connection, the false value is returned correctly, if the app is opened with internet connection active and the device lost its internet connection happens the same thing of the case A (also if I try to terminate and restart the App... I don't know why, I suppose that something remains cached)

All this seems related to the fact Java URLConnection doesn't provide no fail-safe timeout on reads. Looking at the sample at this link I have seen that uses a thread to interrupt the connection in some way but if I add simply the line new Thread(new InterruptThread(Thread.currentThread(), con)).start(); like in the sample nothing changes.

解决方案

static public boolean isServerReachable(Context context) {
    ConnectivityManager connMan = (ConnectivityManager) 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;
}

or by using runtime:

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

You can try isReachable() but there is a bug filed for it and this 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;
}

这篇关于如何快速检查URL服务器可用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆