How to properly close HttpURLConnection on Android
<p>I'm using HttpURLConnection for querying back-end server. Requests are POST. My code looks like:</p>

<pre><code>InputStream is = null;
HttpURLConnection connection = null;
try {
    connection = (HttpURLConnection)new URL(uri).openConnection();
    connection.setRequestMethod("POST");
    connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=" + ENCODING);
    connection.setDoOutput(true);
    byte[] content = buildFormUrlEncoded(params);
    connection.setRequestProperty("Content-Length", String.valueOf(content.length));

    connection.connect();

    OutputStream os = null;
    try {
        os = connection.getOutputStream();
        os.write(content);
    } finally {
        if (os != null) { os.close(); }
    }

    is = connection.getInputStream();
    handle(is);
} finally {
    if (is != null) { is.close(); }
    if (connection != null) { connection.disconnect(); }
}
</code></pre>

<p>However I'm getting this StrictMode error:</p>

<pre><code>A resource was acquired at attached stack trace but never released. See java.io.Closeable for information on avoiding resource leaks.
java.lang.Throwable: Explicit termination method 'close' not called
    at dalvik.system.CloseGuard.open(CloseGuard.java:184)
    at org.apache.harmony.xnet.provider.jsse.OpenSSLSocketImpl.startHandshake(OpenSSLSocketImpl.java:300)
    at org.apache.harmony.xnet.provider.jsse.OpenSSLSocketImpl.startHandshake(OpenSSLSocketImpl.java:257)
    at libcore.net.http.HttpConnection.setupSecureSocket(HttpConnection.java:210)
    at libcore.net.http.HttpsURLConnectionImpl$HttpsEngine.makeSslConnection(HttpsURLConnectionImpl.java:477)
    at libcore.net.http.HttpsURLConnectionImpl$HttpsEngine.connect(HttpsURLConnectionImpl.java:432)
    at libcore.net.http.HttpEngine.sendSocketRequest(HttpEngine.java:282)
    at libcore.net.http.HttpEngine.sendRequest(HttpEngine.java:232)
    at libcore.net.http.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:80)
    at libcore.net.http.HttpsURLConnectionImpl.connect(HttpsURLConnectionImpl.java:164)
</code></pre>

<p>When I am debugging code, <code>os.close()</code>, <code>is.close()</code> and <code>connection.disconnect()</code> is called.</p>

<p>Could StrictMode happen because of connection is keep alive in pool?</p>

<p><strong>EDIT</strong></p>

<ul>
<li>If <code>connection.setRequestProperty("connection", "close");</code> is added the StrictMode error disappear.</li>
<li>If http URL instead of https URL is used the StrictMode error disappear.</li>
<li>If <code>BufferedReader</code> is used the StrictMode error happens less often.</li>
</ul>

<p>I would like to keep https for security and keep alive to reduce handshake overhead.</p>

<p><strong>EDIT 2</strong></p>

<p>Looks like this occurs only in case of android 3.X and 4.0.X.</p>
