现在,我正在就Java I / O进行性能改进。我对使用Java I / O通过网络读取/写入流有一些疯狂的疑问,如下所述。我脑海中浮现出几种观点。但我想清除所有这些
码
URL url = new URL("http://example.com/connector/url2Service");
URLConnection urlConnection = url.openConnection(); // Position 1
HttpURLConnection httpURLConnection = (HttpURLConnection)urlConnection;
String requestStr = buildRequestString();// Position 2
ByteArrayOutputStream rqByteArrayOutputStream = new ByteArrayOutputStream();
rqByteArrayOutputStream.write(((String)requestStr).getBytes()); // Position 3
httpURLConnection.setDoOutput(true);
httpURLConnection.setUseCaches(false);
httpURLConnection.setDoInput(true);
httpURLConnection.setRequestMethod("POST");
rqByteArrayOutputStream.writeTo(httpURLConnection.getOutputStream()); // Position 4
// Waiting for the response.
InputStream inputStream = httpURLConnection.getInputStream(); // Position 5
ByteArrayOutputStream rsByteArrayOutputStream = new ByteArrayOutputStream();
byte[] buffer = new byte[4096];
int length = 0;
while ((length = inputStream.read(buffer)) != -1) { // Position 6
rsByteArrayOutputStream.write(buffer, 0, length);// Position 7
}
String response = new String(rsByteArrayOutputStream.toByteArray());// Position 8
我的理解
我的问题
参考文献:
建立连接时,请求可能会缓存在系统缓冲区中,因此直到通过位置6时,才能保证请求的“上传”发送完成。在这一点上,您知道get请求已经完成。由于服务器现在正在发送响应,因此已收到该消息。传递位置4仅表示您的程序已将请求传递到您自己的系统缓冲区中。
在位置6的最后一次返回流结束时,已收到响应-“下载”完成。
当您退出位置5时,可能会或可能不会收到响应。您要做的就是获得对已存在的输入流的显式访问。可能已经完全接收到响应并将其缓冲在系统TCP缓冲区中,并且有可能还没有收到响应。
您将必须从位置4到位置6的最后一次迭代打开网络资源。在您的代码中,您将继续无限期地保持连接打开状态。退出位置6/7while
循环后,可以通过关闭连接来节省网络资源。
(a)不用理会rqByteArrayOutputStream。而是将连接的输出流包装在OutputStreamWriter中,然后将请求字符串直接写入该流。这样可以节省几行代码,并消除了复制请求字符串的一次迭代。
(b)完成输出流和输入流后,对它们调用close(),以释放网络资源。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句