Reg*_*kie 7 android urlconnection httpurlconnection android-networking
我正在从我的应用程序中逐字复制这个方法,这个方法还没有完成,但如果事情不顺利,它会尝试为我提供超时堆栈跟踪:
protected boolean isHttpAlive() {
boolean isHttpOk = false;
HttpURLConnection httpConnection = null;
try {
URL gurl = new URL("http://www.amazon.com/");
URLConnection connection = gurl.openConnection();
connection.setConnectTimeout(5 * 1000); // 5 seconds!
httpConnection = (HttpURLConnection) connection;
int responseCode = httpConnection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK)
isHttpOk = true;
}
catch (Exception e) {
e.printStackTrace();
}
finally {
if (httpConnection != null)
httpConnection.disconnect();
}
return isHttpOk;
}
Run Code Online (Sandbox Code Playgroud)
现在在我的一个测试设备(Droid)上,当出现问题时,我确实得到了异常,但仅在6分36秒之后,而不是我在上面的代码中设置的5秒.
为此抛出超时异常getResponseCode().
为什么?
我错过了什么?
我最好的猜测是,您连接到的URL,在这种情况下,亚马逊有多个IP地址.
根据文档中的警告:
如果主机名解析为多个IP地址,则此客户端将按RFC 3484顺序尝试每个地址.如果连接到这些地址中的每一个都失败,则在连接尝试引发异常之前将经过多次超时.支持IPv6和IPv4的主机名始终至少有2个IP地址.
编辑:
我仍在研究这个,因为我想将我的应用程序转换HTTPClient为URLConnection.在你的实例中,我不满意超时6分钟.
我也偶然发现了这个博客.他建议加入connection.setReadTimeout(READ_TIMEOUT_MILLISECONDS);,不知道这对你的情况是否有帮助.
| 归档时间: |
|
| 查看次数: |
2024 次 |
| 最近记录: |