我正在使用HttpURLConnection
以下代码检查服务器 URL 是否可用:
try {
boolean connectionFailed = false;
URL knownURL = new URL("http://www.google.com");
httpConnection = (HttpURLConnection) knownURL.openConnection();
httpConnection.setConnectTimeout(5000);
responseCode = httpConnection.getResponseCode();
if (responseCode != 200) {
status = ConnectionStatus.NOT_CONNECTED;
}
}
catch(Exception e) {
connctionFailed = true;
}
此代码在正常情况下工作正常。但是当没有互联网连接时(因为路由器断开或不是热点),httpConnection.getResponseCode()
不执行(函数不返回)。我怎样才能解决这个问题?