1. 程式人生 > >Idea使用HttpClicnt模擬下載檔案:

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