3
嗨我正在使用下面的代碼來建立一個url連接。但隨機我得到responseCode -1(這是responseCode的默認值):HttpURLConnection響應代碼是隨機-1
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()'後設置最近一次,在檢查響應代碼之前可以移動它。 – harism