如何通过HTTP下载文件并将其内容存储在Java中的String中 [英] How to download a file over HTTP and store its content in a String in Java

查看:126
本文介绍了如何通过HTTP下载文件并将其内容存储在Java中的String中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试通过HTTP下载文件,并将其内容存储在字符串中,如标题所示。我的方法是:

  URL u =新的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();

当尝试从流中读取时,代码将失败,报告流关闭。 >

如果您尝试通过浏览器访问该文件,则不会将其作为文本,而不是作为要下载的文件。



我没有在任何地方搜索网页,所以有一点洞察力将不胜感激!



谢谢。

解决方案

查看来自Apache Commons的HttpClient ,特别是 getResponseBodyAsString()方法。


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.

解决方案

Check out HttpClient from Apache Commons, in particular the getResponseBodyAsString() method.

这篇关于如何通过HTTP下载文件并将其内容存储在Java中的String中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆