Java HttpURLConnection关闭IO流
我不熟悉Java和HttpURLConnection。我是否应该在断开连接之前关闭打开的IO流。如果我关闭流,我是否也需要断开连接?哪一种是正确的实施方式Java HttpURLConnection关闭IO流,java,sockets,stream,connection,httpurlconnection,Java,Sockets,Stream,Connection,Httpurlconnection,我不熟悉Java和HttpURLConnection。我是否应该在断开连接之前关闭打开的IO流。如果我关闭流,我是否也需要断开连接?哪一种是正确的实施方式 try { String uri = "http://localhost:8081/RESTEASY/saju/post/text"; URL url = new URL(uri); connection = (HttpURLConnection) url.openConnection(); connection.setRequest
try {
String uri = "http://localhost:8081/RESTEASY/saju/post/text";
URL url = new URL(uri);
connection =
(HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Accept", "text/plain");
connection.setRequestProperty("Content-Type", "text/plain");
connection.setDoOutput(true);
OutputStream os = connection.getOutputStream();
//bla bla
System.out.println(connection.getResponseCode());
InputStream iStream = connection.getInputStream();
//bla bla
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
// os.close(); - IS THIS REQUIRED
// iStream.close(); - IS THIS REQUIRED
connection.disconnect();
}
}
使用完输入/输出/错误流后,应调用输入/输出/错误流上的
close()
断开连接更为复杂。根据javadoc fordisconnect()
:
“表示在不久的将来不太可能向服务器发出其他请求。”
这就是认识到HTTP 1.1规范具有“持久连接”功能,允许在对同一服务器的请求序列中使用相同的TCP/IP连接。(这是透明的)当您调用disconnect
时,很可能会被视为关闭连接的提示
因此,从资源和性能的角度来看:
- 如果您不可能向同一服务器发送另一个请求,最好调用
断开连接
- 如果在不久的将来可能会有另一个请求,这是一个坏主意