HttpURLConnection 下载文件

            String fileUrl = request.getRequestURL().substring(0,
                    request.getRequestURL().indexOf("/rest"))
                    + "/test/resources/images/template.jpg";
            URL url = new URL(fileUrl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.connect();
            response.reset();
            response.setContentType("application/x-msdownload");
            response.addHeader("Content-Disposition", "attachment; filename="
                    + new String("template.jpg".getBytes("gbk"), "iso-8859-1"));
            OutputStream os = response.getOutputStream();
            InputStream in = conn.getInputStream();
            byte[] b = new byte[1024];
            int r = 0;
            while ((r = in.read(b)) != -1) {
                os.write(b, 0, r);
            }
            os.flush();
            os.close();
            in.close();
            conn.disconnect();

 

posted on 2015-02-10 11:15  天凉好个球  阅读(303)  评论(0编辑  收藏  举报

导航