我有一个 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明确指出
But if the response body is long and you are not interested in the rest of it after seeing the beginning, you can close the InputStream
如果我不读取流,服务器很快就会达到最大连接数 (50) 并达到 99% 的工作负载,但如果我读取流,则工作正常。我的错误是什么?
编辑:到目前为止失败的解决方案尝试(其中大部分感谢@Blackbelt)
- 在
finally
block 中调用conn.disconnect()
- 在
finally
block 中调用conn.disconnect()
而不是is.close()
- 在第一次调用之前设置
System.setProperty("http.keepAlive", "false");
- 连接前设置
conn.setRequestProperty("Connection", "Close");
- 在使用的后端服务器 (Civetweb) 上设置
"{enable_keep_alive", "no"}
最佳答案
你也应该调用disconnect()
。根据文档
Disconnect. Once the response body has been read, the HttpURLConnection should be closed by calling disconnect(). Disconnecting releases the resources held by a connection so they may be closed or reused.
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();
}
}
如果您仍然遇到问题,该错误也可能是在后端
关于java - 如何在不读取的情况下关闭持久 HTTP 连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35268980/