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);
           }

你可能感兴趣的:(java)