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()方法即可。

猜你喜欢

转载自blog.csdn.net/weixin_42334396/article/details/84258640