Idea使用HttpClicnt模拟下载文件:

感觉没啥用,不过还是写一下吧,回忆起来就写一下,模拟前提是已经搭建好SpringMVC环境配置:
1、在DownFileDemo类里写:

 @Test
    public void downFile() throws IOException {
        //1、得到HttpClient对象
        CloseableHttpClient httpclient= HttpClients.createDefault();
        //2、创建Httpget对象(发出GET请求,请求的地址)
        HttpGet httpget=new HttpGet("http://localhost:8080/downFile?filename=bground2.jpg");
        //3、得到响应对象HttpResponse
        HttpResponse httpresponse = httpclient.execute(httpget);
        //4、得到实体对象
        HttpEntity entity=httpresponse.getEntity();
        //5、得到文件的InputStream流
        InputStream in = entity.getContent();
        //6、得到一个路径先,存放服务器返回的文件,名字需要自己定义
        File file=new File("D:\\files\\IO练习文件\\photo\\getServerFile.jpg");
        FileOutputStream out=new FileOutputStream(file);
        int len=0;
        byte[] temp=new byte[1024];
        while((len=in.read(temp))!=-1){
            out.write(temp, 0, len);
        }
        //7、刷新输出流
        out.flush();
        //8、关闭输出流
        out.close();
        //9、关闭输入流
        in.close();
        //10、关闭网络连接
        httpclient.close();
        System.out.println("文件下载OK");
    }

2、controller那边写:

//客户端下载文件请求
    @RequestMapping("/downFile")
    public String  downFile( String filename, HttpServletRequest request, HttpServletResponse response) throws IOException {
        //这里路径与上传时有点区别,服务器会自动把webapp/images下的文件加载到服务器,根据你的名字拼接完整即可
        String serverPath = request.getSession().getServletContext().getRealPath("images");
        File file=new File(serverPath,filename);
        System.out.println("客户端请求文件名:"+filename+"\n找到服务器存储文件的位置:"+file);
        //把文件写给前台
        ServletOutputStream os = response.getOutputStream();
        FileInputStream fis=new FileInputStream(file);
        byte[] byt=new byte[1024];
        int leng=0;
        while((leng=fis.read(byt))!=-1){
            os.write(byt,0,leng);
        }
        os.flush();
        os.close();
        fis.close();
        return "downResult";
    }

3、先启动controller那边的controller方法,然后再run DownFile()方法即可。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值