【问题标题】:OkHttpClient connection leak warning from HttpURLConnection来自 HttpURLConnection 的 OkHttpClient 连接泄漏警告
【发布时间】:2018-11-23 00:17:26
【问题描述】:

我正在使用HttpURLConnection 从服务器检索一些配置。它工作正常,但由于某种原因,我在 logcat 中收到以下警告:

OkHttpClient:与...的连接已泄露。您是否忘记关闭响应正文?

正如this 问题中所指出的,Android 在HttpUrlConnection 内部使用OkHttp。我在做什么导致这个警告?

这是我正在使用的代码:

    HttpURLConnection connection = null;
    OutputStream outputStream = null;
    String result;
    try {
        URL url = new URL(CONFIG_URL);
        connection = (HttpURLConnection) url.openConnection();
        connection.setReadTimeout(READ_TIMEOUT_MILLI);
        connection.setConnectTimeout(CONNECT_TIMEOUT_MILLI);
        connection.setRequestMethod(REQUEST_METHOD);

        connection.setDoInput(true);

        connection.addRequestProperty("Content-Type", "application/json");
        connection.addRequestProperty("Accept", "application/json");

        outputStream = connection.getOutputStream();
        try (DataOutputStream wr = new DataOutputStream(outputStream)) {
            wr.write(data.toString().getBytes(STRING_ENCODING));
            wr.flush();
            wr.close();

            int responseCode = connection.getResponseCode();

            if (responseCode != HttpsURLConnection.HTTP_OK) {
                Log.e(TAG, "HTTP error code: " + responseCode);
                return;
            }

            try (InputStream stream = connection.getInputStream()) {
                if (stream != null) {
                    result = readStream(stream, READ_STREAM_MAX_LENGTH_CHARS);
                    //...
                    connection.disconnect();
                }
            } catch (Throwable e) {
                Log.e(TAG, "run: failed to parse server response: " +e.getMessage());
            }
        }
    } catch (Exception e) {
        Log.e(TAG, "HttpSendTask: failed to send configuration request " + data +": " +e.getMessage());
    } finally {
        if (outputStream != null) {
            try {
                outputStream.flush();
                outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (connection != null) {
            connection.disconnect();
        }
    }

【问题讨论】:

  • 绝对是正确的应用程序并且没有依赖项(HttpURLConnection 是 java.io 的一部分)
  • @tyczj 不是重复的。编辑了问题。
  • 你是怎么解决这个问题的?
  • @Keselme 不幸的是我没有。我遇到的最有用的事情是使用正则表达式来过滤这些行。
  • 实际上我找到了一个对我有用的解决方案,在阅读了这个博客之后:blog.csdn.net/Gaugamela/article/details/78482564(我不得不翻译,因为它是在一些亚洲语言中),我发现泄露的连接是输入流,所以当我关闭输入字符串时,那个警告就消失了。从您的代码中,我看到您只关闭了输出流。

标签: android networking httpurlconnection okhttp


【解决方案1】:

关闭连接的输入流解决了我的问题。 尝试在 finally 块中关闭它:

connection.getInputStream().close()

【讨论】:

    猜你喜欢
    • 2016-11-17
    • 2011-10-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-27
    • 1970-01-01
    • 2012-12-07
    • 2018-07-26
    相关资源
    最近更新 更多