异常后使用java http连接实例

Shc*_*ein 9 java urlconnection httpurlconnection httpsurlconnection

以下代码是否安全:

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();
        ...
    }
}
Run Code Online (Sandbox Code Playgroud)

特别是,在InterruptedIOException(例如,读取超时)的情况下调用类似的方法getContentEncoding()是否安全?据我所知,这种方法需要实时连接来读取HTTP(S)头.

更新(附加信息):

这个问题源于真实的系统体验.我相信,系统是在Oracle/Sun JVM 1.6上运行的.代码几乎相同:

...    
} catch (IOException e) {
    if(conn != null) {
         try {
             String response = tryGetResponse(conn);
...
Run Code Online (Sandbox Code Playgroud)

在这个问题发生tryGetResponseHTTPS请求:

 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);
    }
}
Run Code Online (Sandbox Code Playgroud)

自发系统挂在getContentEncoding()呼叫中的套接字连接(或读取)上:

in = Utils.wrapCompressedStream(err, conn.getContentEncoding());
Run Code Online (Sandbox Code Playgroud)

完全在SocketTimeoutException初始代码中抛出后.

因此,似乎getContentEncoding()尝试(或在Java 6中尝试)建立新连接而不设置超时.

jav*_*ker 0

catch (IOException e) {
    if(conn != null) {
        conn.getContentEncoding();
        conn.getErrorStream();
        conn.whateverOtherMethodThere();
        ...
    }
Run Code Online (Sandbox Code Playgroud)

公共类 InterruptedIOException 扩展 IOException

表示 I/O 操作已中断。抛出 InterruptedIOException 表示输入或输出传输已终止,因为执行该传输的线程被中断。bytesTransferred 字段指示在中断发生之前已成功传输了多少字节。

这意味着如果发生中断异常,您将无法对 HttpUrlConnection 进行进一步处理。

同样,通过 IOException 您无法捕获其他类型的异常,例如 IllegalArgumentException、非法线程状态异常等等。

有关更多详细信息http://download.java.net/jdk7/archive/b123/docs/api/java/net/HttpURLConnection.html#getRequestMethod%28%29