gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 06:39:24 26 4
gpt4 key购买 nike

我有一个来自 HttpURLConnection 的输入流。 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框架关闭(?)。

最佳答案

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

Read/convert an InputStream to a String

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

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

关于Java inputStream 作为对象属性,关闭 HttpURLConnection,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19292802/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com