我有一个URLConnection,我想取消它取决于响应代码而不读取任何数据。我密切关注android training以构建以下最小示例 使用请求充斥服务器,因为没有连接被释放回句柄池以供重用
private String downloadUrl(String myurl) throws IOException {
InputStream is = null;
try {
URL url = new URL(myurl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000 /* milliseconds */);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setRequestMethod("GET");
conn.setDoInput(true);
// Starts the query
conn.connect();
int response = conn.getResponseCode();
Log.d(TAG, "The response code is: " + response);
is = conn.getInputStream();
// Do not read anything //String contentAsString = readIt(is, len);
String contentAsString = "notReadingAnything";
return contentAsString;
} finally {
if (is != null) {
is.close();
}
}
}
private class DownloadWebpageTask extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... urls) {
try {
String result = new String();
for (int i=0; i<100; i++) {
result += downloadUrl(urls[0]);
}
return result;
} catch (IOException e) {
return "Unable to retrieve web page. URL may be invalid.";
}
}
@Override
protected void onPostExecute(String result) {
Log.d(TAG, "The response is: " + result);
}
}
尽管明确说明了docs
但是如果响应主体很长并且在看到开头后你对其余部分不感兴趣,你可以关闭InputStream
服务器快速达到其最大连接数(50),如果我不读取流,则工作量达到99%,但如果我读取它,则工作正常。我的错是什么?
编辑:到目前为止尝试解决方案失败(感谢@Blackbelt的大多数人)
conn.disconnect()
区块中调用finally
conn.disconnect()
区块is.close()
而非finally
System.setProperty("http.keepAlive", "false");
conn.setRequestProperty("Connection", "Close");
"{enable_keep_alive", "no"}
答案 0 :(得分:2)
你也应该致电disconnect()
。根据文件
断开连接。一旦阅读了响应主体,就可以了 应该通过调用disconnect()来关闭HttpURLConnection。 断开连接释放连接所拥有的资源,以便它们可以 被关闭或重复使用。
InputStream is = null;
HttpURLConnection conn = null;
try {
URL url = new URL(myurl);
conn = (HttpURLConnection) url.openConnection();
} finally {
if (is != null) {
is.close();
}
if (conn != null) {
conn.disconnect();
}
}
如果您仍然遇到问题,那么该错误也可能是后端