java - 如何在不读取的情况下关闭持久 HTTP 连接

标签 java android httpconnection

我有一个 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)

  1. finally block 中调用conn.disconnect()
  2. finally block 中调用conn.disconnect()而不是is.close()
  3. 在第一次调用之前设置System.setProperty("http.keepAlive", "false");
  4. 连接前设置conn.setRequestProperty("Connection", "Close");
  5. 在使用的后端服务器 (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/

相关文章:

java - Java 中的 TCP 服务器

java - 确定列表是否至少包含数组中包含的一项的快速方法

java - Android查看performClick()和callOnClick()的区别

android - 布局预览器中未呈现 "Material Design Components"

java - 更改最大http线程数jboss AS6.1.0.Final

android - WebView 的 UI 和 HTTP 线程是否可以分开?

java - printf 将空格附加到字符串的末尾

java - 我可以将字符串数组 (String[][]) 传递给 Java 中的函数吗?

android应用程序在 Release模式下强制关闭

java - HTTPConnection何时执行以及它的状态是什么