在我的应用我的AsyncTask类,连接到本地/远程服务器,以获得一些数据,我想检查服务器连接的AsyncTask运行之前, 我有这样的功能:如何检查服务器连接是否存在?
public static boolean checkServerAvailable(String hostURL) {
HttpURLConnection connection = null;
try {
URL u = new URL(hostURL);
connection = (HttpURLConnection) u.openConnection();
connection.setConnectTimeout(5000);
connection.setRequestMethod("HEAD");
int code = connection.getResponseCode();
System.out.println("" + code);
return true;
// You can determine on HTTP return code received. 200 is success.
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return false;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return false;
} finally {
if (connection != null) {
connection.disconnect();
}
}
}
此功能使用超时连接到服务器,如果超时过期,则意味着没有服务器。问题是我运行这个代码,即使服务器存在,它也会返回“没有服务器”。
我试过设置一个5000ms大的超时时间,但它很长时间会暂停UI,有时甚至在服务器存在时仍然会返回“没有服务器”。
我该怎么办? 谢谢!
可能是您的互联网连接有问题。 – AKSiddique
这三个catch块中的哪一个会进入,并抛出什么异常? – EJP
'它正在返回“没有服务器”。不可能。该函数返回true或false。 – greenapps