Java inputStream作为对象属性,关闭HttpURLConnection

时间:2013-10-10 10:03:15

标签: java struts2 struts inputstream httpurlconnection

我有来自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对象,但是主动进行一些内务管理是很好的。我还假设传递给代理对象的“new BufferedInputStream”将由底层struts框架(?)关闭。

2 个答案:

答案 0 :(得分:1)

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

Read/convert an InputStream to a String

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

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

答案 1 :(得分:1)

看起来更干净的方法是对输入流进行子类化并覆盖关闭。这样当struts调用close时,在读完流后,你可以关闭你的连接:

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参数的流。