バックエンド サーバーのクエリに HttpURLConnection を使用しています。リクエストは POST です。私のコードは次のようになります:
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(); }
}
ただし、次の StrictMode エラーが発生します。
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)
コードをデバッグしているとき、os.close()
、is.close()
およびconnection.disconnect()
が呼び出されます。
プールで接続が維持されているために StrictMode が発生する可能性はありますか?
編集
- を追加すると、 StrictMode
connection.setRequestProperty("connection", "close");
エラーが消えます。 - https URL の代わりに http URL を使用すると、StrictMode エラーは表示されなくなります。
- を使用する
BufferedReader
と、StrictMode エラーの発生頻度が低くなります。
セキュリティのために https を維持し、ハンドシェイクのオーバーヘッドを減らすために維持したいと考えています。
編集2
これは、android 3.X および 4.0.X の場合にのみ発生するようです。