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

And*_*eaF 22 java android http url-validation

我在表单中有一个URL

http://www.mywebsite.com/util/conv?a=1&from=%s&to=%s
Run Code Online (Sandbox Code Playgroud)

并想检查它是否可用.

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

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


我试过了

boolean reachable = InetAddress.getByName(myLink).isReachable(6000);
Run Code Online (Sandbox Code Playgroud)

但总是回报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;
    }
}
Run Code Online (Sandbox Code Playgroud)

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

编辑

我明白慢慢的原因是什么

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

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

所有这些似乎与事实相关,Java URLConnection 并未在读取时提供无故障安全超时.看看这个链接上的示例我已经看到使用线程以某种方式中断连接,但如果我添加简单new Thread(new InterruptThread(Thread.currentThread(), con)).start();的样本中的行没有任何变化.

Sag*_*wal 25

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;
}
Run Code Online (Sandbox Code Playgroud)

或者使用运行时:

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;
}
Run Code Online (Sandbox Code Playgroud)

你可以试试,isReachable()但是有一个bug提交给它,这个评论说isReachable()需要root权限:

try {
    InetAddress.getByName("your server url").isReachable(2000); //Replace with your name
    return true;
} catch (Exception e)
{
    return false;
}
Run Code Online (Sandbox Code Playgroud)


小智 5

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;
        }
    }
Run Code Online (Sandbox Code Playgroud)