用Java流式传输HTTP响应 [英] Stream a HTTP response in Java
问题描述
我想将对HTTP请求的响应写到文件.但是我想将响应流式传输到物理文件,而不必等待整个响应被加载.
I want to write the response on an HTTP request to a File. However I want to stream the response to a physical file without waiting for the entire response to be loaded.
我实际上将向JHAT服务器发出请求,以从转储中返回所有字符串.我的浏览器在响应完成之前就挂起了,因为有70k这样的对象,我想将它们写到文件中以便扫描.
I will actually be making a request to a JHAT server for returning all the Strings from the dump. My browser hangs before the response completes as there are 70k such objects, I wanted to write them to a file so that I can scan through.
预先感谢
推荐答案
从HTTP流中读取有限数量的数据并将其写入文件流.直到所有数据都处理完毕.
Read a limited amount of data from the HTTP stream and write it to a file stream. Do this until all data has been handled.
以下是演示该原理的示例代码.在此示例中,我不处理任何I/O错误.我选择了8KB的缓冲区,它比每次处理一个字节要快,但仍然限制了每次迭代期间拉入RAM的数据量.
Here is example code demonstrating the principle. In this example I do not deal with any i/o errors. I chose an 8KB buffer to be faster than processing one byte at a time, yet still limiting the amount of data pulled into RAM during each iteration.
final URL url = new URL("http://example.com/");
final InputStream istream = url.openStream();
final OutputStream ostream = new FileOutputStream("/tmp/data.txt");
final byte[] buffer = new byte[1024*8];
while (true) {
final int len = istream.read(buffer);
if (len <= 0) {
break;
}
ostream.write(buffer, 0, len);
}
这篇关于用Java流式传输HTTP响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!