如何像这样关闭HttpsURLConnection:
HttpsURLConnection con = null;
try {
URL url = new URL(externalUrl);
con = (HttpsURLConnection) url.openConnection();
return IOUtils.toString((con.getInputStream());
} catch (IOException e) {
if (con != null) {
return IOUtils.toString((con.getErrorStream());
}
}发布于 2020-07-17 18:00:04
首先,我想提一下,您问题中的代码甚至没有编译,因为在执行IOUtils.toString((con.getInputStream());和IOUtils.toString((con.getErrorStream());时会有额外的括号
现在来谈谈如何关闭连接的问题。因为,HttpsURLConnection没有实现Closeable接口,所以把它放在带有资源块的try中不会对你有帮助。您需要在块中关闭连接。
这将服务于您的目的:
HttpsURLConnection con = null;
InputStream is = null;
InputStream errorStream = null;
try {
URL url = new URL(externalUrl);
con = (HttpsURLConnection) url.openConnection();
is = con.getInputStream();
return IOUtils.toString(is, Charset.defaultCharset());
} catch (IOException e) {
if (con != null) {
errorStream = con.getErrorStream();
return IOUtils.toString(errorStream,Charset.defaultCharset());
}
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
}
}
if (errorStream != null) {
try {
errorStream.close();
} catch (IOException e) {
}
}
if (con != null) {
con.disconnect();
}
}注意-使用 disconnect**.时,有一些注意事项请阅读[here](https://techblog.bozho.net/caveats-of-httpurlconnection/) .**中的内容
最后一个建议,请避免使用不推荐使用的方法。IOUtils.toString(inputStream)方法是弃用的,您应该改用IOUtils.toString(inputStream,charset)
https://stackoverflow.com/questions/62951453
复制相似问题