![](/img/trans.png)
[英]Does closing a BufferedOutputStream also close the underlying OutputStream?
[英]Does closing of input/output stream gotten from getInput/OutputStream() affects recreation of underlying Socket?
我已经浏览过描述Java中HttpURLConnection
工作细节的资源,因此在Android中(那里没有使用连接池的默认实现),我的问题是:如果我关闭从HttpURLConnection
获得的流,系统是否会在下一次使用相同的URL
建立HttpURLConnection
时创建一个新的Socket
,否则它将尝试使用一个存在的Socket
? 考虑以下代码:
private byte[] downloadText(URL url, String data) {
OutputStream out = null;
InputStream in = null;
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
try {
conn.setRequestMethod("POST");
conn.setReadTimeout(20 * 1000);
conn.setConnectTimeout(15 * 000);
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setRequestProperty("Content-Type", "application/json;charset=utf-8");
byte[] payload = data.getBytes("utf-8");
conn.setFixedLengthStreamingMode(payload.length);
conn.connect();
out = new BufferedOutputStream(conn.getOutputStream());
out.write(payload);
out.flush();
final int responseCode = conn.getResponseCode();
final String responseMessage = conn.getResponseMessage();
is = conn.getInputStream();
if((responseCode / 100) == 2 || responseMessage.equals("OK")) {
return readFromStream(is);
}
} catch (IOException e) {
Log.e(TAG, "Error occurred while trying to connect to the server" + e.toString());
} finally {
try {
if(out != null) {
out.close();
}
if(is != null) {
is.close();
}
} catch(IOException e) {
Log.e(TAG, "Error occurred while trying to close data streams" + e.toString());
}
}
}
您的问题没有道理。 如果没有连接池,则没有“现有套接字”可重用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.