来自HttpURLConnection的OkHttpClient连接泄漏警告

时间:2018-06-13 12:03:31

标签: android networking httpurlconnection okhttp

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

  

OkHttpClient:与...的连接泄露。你忘了关闭一个回复机构吗?

正如this问题所述,Android在OkHttp内部使用HttpUrlConnection。我该怎么做才能引起这个警告?

以下是我使用的代码:

    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();
        }
    }

0 个答案:

没有答案
相关问题