【发布时间】:2011-11-09 14:49:22
【问题描述】:
您好,我正在使用以下代码建立 url 连接。但随机我得到 responseCode -1(这是 responseCode 的默认值):
try {
URL url = new URL(urlString);
HttpURLConnection httpconn = (HttpURLConnection) url.openConnection();
if (httpconn.getResponseCode() == HttpURLConnection.HTTP_OK) {
handleData(new DataInputStream(httpconn.getInputStream()), requestCode);
} else {
Log.e(TAG, "HttpConnection not OK: " + httpconn.getResponseCode());
ActivityHelper.httpError(this);
}
httpconn.disconnect();
} catch (Exception e) {
Log.e(TAG, "handleHttpConnection", e);
ActivityHelper.httpError(this);
}
我做错了吗?因为它在 10 次尝试中估计有 9 次都能完美运行。
【问题讨论】:
-
我猜
url.openConnection()不一定有时间打开底层 http 连接。您可以尝试在打开后添加httpconn.connect()。或者响应代码应该设置为最新,一旦你调用了httpconn.getInputStream(),可以在检查响应代码之前移动它。