HttpURLConnection下載網絡文件

@RequestMapping(value = "/downloadFingerPlugIn.jspx")
public void downloadFingerPlugIn(HttpServletRequest request, HttpServletResponse response) {
           try {
               // 統一資源
               String fingerPlugInUrl = ParamUtil.getParam("fingerPlugInUrl");
               URL url = new URL(fingerPlugInUrl);
               // 連接類的父類,抽象類
               URLConnection urlConnection = url.openConnection();
               // http的連接類
               HttpURLConnection conn = (HttpURLConnection) url
                       .openConnection();
               conn.connect();

               OutputStream outputStream = null;

               // 文件名
               String filePathUrl = conn.getURL().getFile();
               String fileFullName = filePathUrl.substring(filePathUrl.lastIndexOf(File.separatorChar) + 1);
               URLConnection con = url.openConnection();
               BufferedInputStream bin = new BufferedInputStream(conn.getInputStream());

               String zipName = "plugIn.zip";
               response.reset();
               response.setHeader("Content-Disposition", "attachment; filename=\"" + zipName + "\"");
               response.addHeader("Content-Length", "" + con.getContentLength());
               response.setContentType("application/octet-stream;charset=UTF-8");
               outputStream = new BufferedOutputStream(response.getOutputStream());
               int size = 0;
               int len = 0;
               byte[] buf = new byte[1024];
               while ((size = bin.read(buf)) != -1) {
                   len += size;
                   outputStream.write(buf, 0, size);
               }
               bin.close();
               outputStream.flush();
               outputStream.close();

           } catch (MalformedURLException e) {
                  logger.error("",e);
           } catch (IOException e) {
                     // TODO Auto-generated catch block
               logger.error("",e);
           }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章