欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

java 下载网络资源

程序员文章站 2022-03-02 21:16:55
...
//下载网络资源
		@RequestMapping("downloadNet")
		@ResponseBody
		public void downloadNet(HttpServletResponse response,String  zlmc,String cclj) throws MalformedURLException {
	        // 下载网络文件
	        int bytesum = 0;
	        int byteread = 0;
	        try {
	        	URL url = new URL(cclj);//http://192.168.1.250:8091/xxx/xx.xx
		        HttpURLConnection conn = (HttpURLConnection)url.openConnection();  
		        //设置超时间为3秒
		        conn.setConnectTimeout(3*1000);
		        //防止屏蔽程序抓取而返回403错误
		        conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");

		        //得到输入流
		        InputStream inputStream = conn.getInputStream();  
		        //获取自己数组
		        byte[] buffer = readInputStream(inputStream);    
	            // 清空response
	            response.reset();
	            // 设置response的Header
	            response.addHeader("Content-Disposition", "attachment;filename="+URLEncoder.encode(zlmc, "UTF-8"));
	            response.setCharacterEncoding("UTF-8");  
	            response.addHeader("Content-Length", "" + buffer.length);
	            OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
	            response.setContentType("application/octet-stream");
	            toClient.write(buffer);
	            toClient.flush();
	            toClient.close();
	            
	        } catch (FileNotFoundException e) {
	            e.printStackTrace();
	        } catch (IOException e) {
	            e.printStackTrace();
	        }

		}

	    /**
	     * 从输入流中获取字节数组
	     * @param inputStream
	     * @return
	     * @throws IOException
	     */
	    public static  byte[] readInputStream(InputStream inputStream) throws IOException {  
	        byte[] buffer = new byte[1024];  
	        int len = 0;  
	        ByteArrayOutputStream bos = new ByteArrayOutputStream();  
	        while((len = inputStream.read(buffer)) != -1) {  
	            bos.write(buffer, 0, len);  
	        }  
	        bos.close();  
	        return bos.toByteArray();  
	    }