Is the following code safe:
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();
...
}
}
Particularly, is it safe in case of InterruptedIOException (say, read timeout) to call methods like getContentEncoding()
? As far as I understand this method requires live connection to read HTTP(S) headers.
Update (additional info):
This question originates from a real-system experience. I believe, the system was run on Oracle/Sun JVM 1.6 then. The code is almost the same:
...
} catch (IOException e) {
if(conn != null) {
try {
String response = tryGetResponse(conn);
...
The problem happened in the tryGetResponse
on HTTPS requests:
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);
}
}
Spontaneously system hanged on the socket connect (or read) in the getContentEncoding()
call:
in = Utils.wrapCompressedStream(err, conn.getContentEncoding());
exactly after SocketTimeoutException
is thrown in the initial code.
So, it seems that getContentEncoding()
tries (or tried in Java 6) to establish a new connection without timeouts being set.