[英]Getting a file from an http request in java
如何調用網址以處理結果?
我有一個獨立的報告servlet,我鏈接到報告。 我想現在通過電子郵件發送這些報告,如果我在瀏覽器中這樣做,我可以使用xhttprequest,並處理結果 - 我基本上想用Java做同樣的事情,但我不知道該如何去做它。
更新 :我想從網址獲取一個文件(無論是pdf還是HTML等)。
更新 :這將完全在服務器上運行 - 沒有觸發電子郵件的請求,而是一個預定的電子郵件。
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();
}
}
編輯:清理代碼。
查看URL和URLConnection類。 這是一些文檔: http : //www.exampledepot.com/egs/java.net/Post.html
如果打算在servlet執行時運行另一個資源而不將控制轉移到另一個資源,則可以嘗試使用include(request,response)。
RequestDispatcher dispatcher =
getServletContext().getRequestDispatcher("/url of other resource");
if (dispatcher != null)
dispatcher.include(request, response);
}
您可以將它放在servlet上,其他資源的結果包含在您的servlet中。
編輯:既然你想找回一個文件,那么這個解決方案也適用於此。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.