OkHttpClient предупреждение об утечке соединения от HttpURLConnection - PullRequest
0 голосов
/ 13 июня 2018

Я использую HttpURLConnection , чтобы получить некоторую конфигурацию с сервера.Это работает нормально, но по какой-то причине я получаю следующее предупреждение в logcat:

OkHttpClient: Соединение с ... утекло.Вы забыли закрыть тело ответа?

Как указано в этом вопросе, 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();
        }
    }
...