我在表单中有一个 URL
http://www.mywebsite.com/util/conv?a=1&from=%s&to=%s
并想检查它是否可用。
如果我尝试使用浏览器打开这些链接,这些链接会将我重定向到错误的请求页面,但是通过代码我可以获得所需的数据。
在 HTTP 请求过程中使用 try-catch block 非常慢,所以我想知道如何 ping 一个类似的地址以检查其服务器是否处于 Activity 状态。
我试过了
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;
}
}
在进程结束时返回正确的值,如果服务器不可用,有点太慢了。
编辑
我已经明白什么是缓慢的原因
a) 如果服务器返回一些数据但在完成请求之前中断了请求,超时将被忽略并卡住,直到返回导致执行到达 catch block 的 Exception
,这是导致这种方法很慢,但我仍然没有找到避免这种情况的有效解决方案。
b) 如果我启动 android 设备并在没有连接的情况下打开应用程序,则正确返回 false 值,如果应用程序在 Internet 连接处于 Activity 状态的情况下打开并且设备失去其 Internet 连接,则与情况 A 相同(如果我尝试终止并重新启动应用程序...我不知道为什么,我想某些东西仍然被缓存)
所有这一切似乎都与 Java URLConnection
没有在读取时提供故障安全超时这一事实有关。查看样本 this link我已经看到使用线程以某种方式中断连接,但是如果我只添加行 new Thread(new InterruptThread(Thread.currentThread(), con)).start();
就像 sample 没有任何变化。
最佳答案
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 it和 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;
}
关于java - 如何快速检查 URL 服务器是否可用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25805580/