java 網絡文件下載

public String goDownLoad() throws IOException, URISyntaxException{
//         String filePath = urlPath;
        
        String filePath ="http://e.hiphotos.baidu.com/pic/w%3D230/sign=e530f6b95d6034a829e2bf82fb1249d9/bba1cd11728b4710c5078274c2cec3fdfc032359.jpg";
        URL _URL=new URL(filePath);  
        HttpURLConnection con=(HttpURLConnection) _URL.openConnection();  
        InputStream fis=con.getInputStream();
        byte[] buffer = new byte[fis.available()];
        fis.read(buffer);
        fis.close();
        //獲取文件名
        String trueurl=con.getURL().toString();
        String filename=trueurl.substring(trueurl.lastIndexOf('/')+1);
        this.getResponse().reset();
        this.getResponse().setHeader("Content-Type", "application/octet-stream");
        this.getResponse().addHeader("Content-Disposition", "attachment;filename="+ new String(filename.getBytes(), "UTF-8"));
        this.getResponse().addHeader("Content-Length", "" + con.getContentLength());
        SimpleDateFormat formate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        this.getResponse().addHeader("Date", formate.format(new Date()));
        OutputStream toClient = this.getResponse().getOutputStream();
        toClient.write(buffer);
        toClient.flush();
        toClient.close();
        return null;
        
    }
發佈了18 篇原創文章 · 獲贊 3 · 訪問量 5萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章