我使用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; }
此代码在正常条件下正常工作.但是当没有Internet连接时(因为路由器断开连接或热点连接),httpConnection.getResponseCode()不会被执行(函数不会返回).我怎样才能解决这个问题?
解决方法
httpConnection.setConnectTimeout(5000)
是连接超时.
是连接超时.
这不是httpConnection.getResponseCode()的超时.
如果添加httpConnection.setReadTimeout(2000),httpConnection.getResponseCode()应在没有可用连接时抛出异常.