我需要使用servlet将数据从外部服务器传输到我的主机。而不是上传文件我需要从另一台服务器下载。 我尝试了正常的下载java程序,但它不起作用
答案 0 :(得分:2)
in servlet
您可以从特定的URL
获取该文件并将其发送给客户端,如下所示:
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException, UnavailableException
{
int bytesRead = 0;
int count = 0;
byte[] buff = new byte[1];
OutputStream out = res.getOutputStream();
res.setContentType("application/contenttype");//i.e: contenttype=pdf,doc,etc" );
String fileURL = "http://someaddress/somefile.someextension";
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
res.setHeader("Content-disposition",
"attachment; filename=somefile.someextension;");
URL url = new URL(fileURL);
bis = new BufferedInputStream(url.openStream());
bos = new BufferedOutputStream(out);
while (-1 != (bytesRead = bis.read(buff, 0, buff.length)))
{
bos.write(bytesRead);
bos.flush();
}
}
注意:您还需要处理相关的例外。