0

我有一个来自 HttpURLConnection 的 inputStream。inputStream 作为属性传递给一个对象,该对象稍后将通过 Struts2 框架的 getter 调用,以将流直接提供给用户浏览器。虽然代码似乎按预期工作,但我担心我无法正确关闭 HttpURLConnection,因为这会使我的输入流在从用户浏览器读取之前无效。代码如下:

private void DownloadOutput(DownloadableObject retVal, URL u, String cookie) {
        try {
            HttpURLConnection conn = (HttpURLConnection) u.openConnection();
            conn.setRequestMethod("GET");
            conn.setRequestProperty("Cookie", cookie);

            Map<String, List<String>> headers =  conn.getHeaderFields();

            retVal.setContentLength(conn.getContentLength());
            retVal.setStream(new BufferedInputStream(conn.getInputStream()));
//          in.close();
//            conn.disconnect();
        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

有什么建议是最佳方法吗?我假设 gc 稍后会清除 HttpURLConnection 对象,但最好主动做一些内务处理。我还假设传递给代理对象的“新 BufferedInputStream”将被底层的 struts 框架(?)关闭。

4

2 回答 2

1

将其转换为字符串,然后将其设置为对象

将 InputStream 读取/转换为字符串

Streams 基本上代表一个句柄输入/输出源,当您关闭引用时,它会丢失句柄

http://docs.oracle.com/javase/tutorial/essential/io/streams.html

于 2013-10-10T10:16:30.800 回答
1

看起来更简洁的方法是对输入流进行子类化并覆盖关闭。这样,当 struts 调用关闭时,在读取流之后,您可以关闭连接:

private class mytest extends  BufferedInputStream {

        private HttpURLConnection aConn;

        public mytest(HttpURLConnection conn, InputStream in) {
            super(in);
            this.aConn = conn;
        }

        public mytest(HttpURLConnection conn, InputStream in, int size) {
            super(in, size);
            this.aConn = conn;
        }

        @Override
        public void close() throws IOException {
            super.close();
            System.out.println("The stream has been closed, time to close the connection");
            aConn.disconnect();
            System.out.println("Connection has been disconnected");
        }
    }

所以上面的对象就是将在动作中设置为 inputStream 参数的流。

于 2013-10-11T16:42:40.593 回答