如何通过HTTP下载文件并将其内容存储在Java的字符串中
正如标题所说,我正在尝试通过HTTP下载文件并将其内容存储在字符串中。因此,我的方法是:
URL u = new URL("http://url/file.txt");
ByteArrayBuffer baf = new ByteArrayBuffer(32);
InputStream in = (InputStream) u.getContent();
BufferedInputStream bis = new BufferedInputStream(in);
int buffer;
while((buffer = bis.read()) != -1){
baf.append((byte)buffer);
}
bis.close();
in.close();
当代码试图从流中读取时,该代码会失败,报告流关闭。
现在,如果您尝试通过浏览器访问文件,则不会用作文本,而是将其作为要下载的文件。
我还没有在此处搜索网络的任何地方,因此对此深表兴趣!
谢谢。
I'm trying to download a file over HTTP and store its contents in a String, as the title says. My approach is thus:
URL u = new URL("http://url/file.txt");
ByteArrayBuffer baf = new ByteArrayBuffer(32);
InputStream in = (InputStream) u.getContent();
BufferedInputStream bis = new BufferedInputStream(in);
int buffer;
while((buffer = bis.read()) != -1){
baf.append((byte)buffer);
}
bis.close();
in.close();
The code fails when it tries to read from the stream, reporting the stream is closed.
Now if you try to access the file through a browser, it won't be served as text, rather as a file to be downloaded.
I haven't gotten anywhere searching the web on this, so a little insight would be much appreciated!
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这是为您提供的代码。除了尝试执行的操作外,它还能够处理GZIP压缩(如果您在标题中使用
接受
Accept-编码:GZIP,DEFLATE
),并且会自动检测为您的编码(处理字符串所需)。该代码来自
info.olteanu.utils.retrieve.retrievepage
,。Here's a piece of code that does that for you. In addition to what you're attempting to do, it is also able to handle GZip compression (if you set it in the headers with
Accept-Encoding: gzip, deflate
) and automatically detects encoding for you (required for handling strings).The code is from
info.olteanu.utils.retrieve.RetrievePage
, Phramer project.尝试此代码,它可能不会编译,因为我没有测试过它,但是在没有捕获所有可能的例外的情况下它应该可以使用,但是您可以轻松添加它。请注意超时,切勿使用无限的超时,因为如果不可用的话,您的程序将来会挂起。如果您做的不仅仅是简单的文本文件检索,则可以查看 apache commons。
Try this code, it might not compile since i've not tested it but it should work beside that all possible Exceptions are not caught, but you can add this easily. Note the timeouts, NEVER use infinite timeouts since your program will hang sometime in the future if the ressource is not available. If you're doing more than a simple text file retrievement you could have a look into HTTPClient of the Apache Commons.
查看 httpclient 来自apache commons,特别是 norefollow noreferrer“
Check out HttpClient from Apache Commons, in particular the getResponseBodyAsString() method.