次のコードは安全ですか:
try {
URL url = new URL(urlRequest);
conn = (HttpURLConnection)url.openConnection();
conn.setConnectTimeout(30000);
conn.setReadTimeout(30000);
conn.setRequestProperty("Accept-Encoding", "gzip, deflate");
String encoding = conn.getContentEncoding();
return Utils.wrapCompressedStream(conn.getInputStream(), encoding);
} catch (IOException e) {
if(conn != null) {
conn.getContentEncoding();
conn.getErrorStream();
conn.whateverOtherMethodThere();
...
}
}
特に、InterruptedIOException (読み取りタイムアウトなど) が発生した場合に、次のようなメソッドを呼び出すのは安全getContentEncoding()
ですか? 私が理解している限り、この方法では HTTP(S) ヘッダーを読み取るためにライブ接続が必要です。
更新 (追加情報):
この質問は、実際のシステムでの経験に由来します。当時、システムは Oracle/Sun JVM 1.6 で実行されていたと思います。コードはほとんど同じです:
...
} catch (IOException e) {
if(conn != null) {
try {
String response = tryGetResponse(conn);
...
HTTPSリクエストtryGetResponse
で問題が発生しました。
private static String tryGetResponse(HttpURLConnection conn) {
if(conn == null) return "(failed to get)";
InputStream in = null;
try {
InputStream err = conn.getErrorStream();
if (err != null) {
in = Utils.wrapCompressedStream(err, conn.getContentEncoding());
}
return Utils.inputStreamToString(in);
} catch (IOException e) {
return "(failed to get)";
} finally {
Utils.closeQuitely(in);
}
}
getContentEncoding()
呼び出し中のソケット接続 (または読み取り) でシステムが自然にハングアップしました。
in = Utils.wrapCompressedStream(err, conn.getContentEncoding());
SocketTimeoutException
初期コードでスローされた直後。
そのため、getContentEncoding()
タイムアウトを設定せずに新しい接続を確立しようとする (または Java 6 で試行した) ようです。