![](/img/trans.png)
[英]Android: SocketException thrown when attempting HttpURLConnection.getOutputStream()
[英]Android - HttpUrlConnection is not closing. Eventually results to SocketException
我在運行Jellybean(4.1 - 4.3)的設備中遇到HttpUrlConnection的一些問題,其中連接未關閉並且在執行多次后導致SocketException“Too many open files”。
我打算調用HttpUrlConnection.disconnect()並關閉finally塊中的所有Inputstream,Outputstream,Reader和Writers。
轉到adb shell並執行netstat
顯示應用程序創建的所有連接都處於CLOSE_WAIT狀態。
InputStream inputStream = httpUrlConnection.getInputStream();
// After calling inputStream.read() then the problem occurs. I think the
// inputstream doesn't get closed even after calling close in a finally block.
// The InputStream is a ChunkedInputStream if that helps.
我嘗試過在2.3.3,4.0.3和4.4上運行的其他設備並沒有遇到這個問題。
還有其他方法可以手動關閉連接嗎?
我終於找到了解決方法。 似乎Jellybean在“Keep-Alive”連接上存在問題。 我剛剛將Connection = Close添加到我的請求標題中,現在一切正常。 做一個netstat,我看到連接現在正在關閉,由於“打開的文件太多”,我不再收到SocketException。
檢查如果你已經嘗試了以下所有...可能有一些東西丟失..其他明智的應該沒有任何問題。
InputStream in;
HttpsURLConnection urlConnection =null;
try {
URL url = new URL(Url);
urlConnection = (HttpsURLConnection) url
.openConnection();
//5 Second timeout
urlConnection.setReadTimeout(5*1000);
in = urlConnection.getInputStream();
int responseCode = urlConnection.getResponseCode();
if (responseCode != HttpURLConnection.HTTP_OK) {
InputStream errInputStream = urlConnection.getErrorStream();
//Print error message and response code..
errInputStream.close();
}
in.close();
} catch (Exception e) {
e.printStackTrace();
} finally{
if(urlConnection != null)
urlConnection.disconnect();
}
你可能最好不要調用disconnect()
,從而允許它進行HTTP連接池。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.