我需要检查网站是否被 ISP 阻止,以便在我的 Android 应用程序中做出正确的决定。
我该怎么做?
最佳答案
试试这个,如果你得到的响应是真的,这是允许的,
public boolean isSiteBlocked() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnected()) {
try {
URL url = new URL("http://www.google.com");
HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
urlc.setConnectTimeout(3000);
urlc.connect();
if (urlc.getResponseCode() == 200) {
return new Boolean(true);
}
// also check different code for down or the site is blocked, example
if (urlc.getResponseCode() == 521) {
// Web server of the site is down
return new Boolean(false);
}
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return false;
}
更新
如果网站宕机或服务器宕机,则必须按要求处理
关于java - 如何以编程方式检查网站是否被阻止?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51472328/