繁体   English   中英

将数据从服务器传输到servlet

[英]Transfer data from server to servlet

我需要使用Servlet将数据从外部服务器传输到我的主机。 而不是上传文件,我需要从另一台服务器下载。 我尝试了普通的下载Java程序,但是没有用

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();

            }
    }

注意:您还需要处理相关的异常。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM