java 从java中的http请求获取文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/238824/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Getting a file from an http request in java
提问by RodeoClown
How do I call a url in order to process the results?
如何调用 url 以处理结果?
I have a stand-alone reporting servlet which I link to for reports. I want to email these reports now, if I were doing this in the browser, I could just use an xhttprequest, and process the results - I basically want to do the same thing in Java, but I'm not sure how to go about it.
我有一个独立的报告 servlet,我将其链接到报告。我现在想通过电子邮件发送这些报告,如果我在浏览器中这样做,我可以只使用 xhttprequest,并处理结果 - 我基本上想用 Java 做同样的事情,但我不知道如何去做它。
UPDATE: I'm looking to get a file back from the url (whether that be a pdf or html etc).
更新:我希望从 url 取回文件(无论是 pdf 还是 html 等)。
UPDATE: This will be running purely on the server - there is no request that triggers the emailing, rather it is a scheduled email.
更新:这将完全在服务器上运行 - 没有触发电子邮件的请求,而是预定的电子邮件。
回答by albertb
public byte[] download(URL url) throws IOException {
URLConnection uc = url.openConnection();
int len = uc.getContentLength();
InputStream is = new BufferedInputStream(uc.getInputStream());
try {
byte[] data = new byte[len];
int offset = 0;
while (offset < len) {
int read = is.read(data, offset, data.length - offset);
if (read < 0) {
break;
}
offset += read;
}
if (offset < len) {
throw new IOException(
String.format("Read %d bytes; expected %d", offset, len));
}
return data;
} finally {
is.close();
}
}
Edit: Cleaned up the code.
编辑:清理代码。
回答by Moishe Lettvin
Check out the URL and URLConnection classes. Here's some documentation: http://www.exampledepot.com/egs/java.net/Post.html
查看 URL 和 URLConnection 类。这是一些文档:http: //www.exampledepot.com/egs/java.net/Post.html
回答by Vincent Ramdhanie
If the intention is to run another resource while your servlet is executing with out transferring control to the other resource you can try using include(request, response).
如果目的是在您的 servlet 执行时运行另一个资源而不将控制权转移到另一个资源,您可以尝试使用 include(request, response)。
RequestDispatcher dispatcher =
getServletContext().getRequestDispatcher("/url of other resource");
if (dispatcher != null)
dispatcher.include(request, response);
}
You may put this on a servlet and the result of the other resource is included on your servlet.
您可以将它放在 servlet 上,而其他资源的结果包含在您的 servlet 中。
EDIT: Since you are looking to get a file back then this solution works for that too.
编辑:由于您希望获取文件,因此此解决方案也适用于该文件。

