JAVA实现网络文件下载

		HttpURLConnection conn = null;
		OutputStream outputStream = null;
		InputStream inputStream = null;
		try {
			String path = r.getParameter("filename");
			File fl = new File(path);
			
			URL url = new URL(path); 
			conn = (HttpURLConnection)url.openConnection();
			inputStream = conn.getInputStream();
			
			rp.reset();
			rp.setHeader("Content-Disposition", "attachment;filename=\""+ fl.getName() + "\"");
			rp.setContentType("application/octet-stream");
			rp.setContentLength((int)conn.getContentLength());
			rp.setHeader("Pragma", "No-cache"); 
			rp.setHeader("Cache-Control", "No-cache"); 
			rp.setDateHeader("Expires", 0);
			
			outputStream = new BufferedOutputStream(rp.getOutputStream());
			byte[] buffer = new byte[4096];    
			int len = 0;
			while((len = inputStream.read(buffer)) != -1) {
				outputStream.write(buffer, 0, len);    
			}
			outputStream.flush();
		} catch(Exception e){
			e.printStackTrace();
		} finally {
			if(conn!=null){
				conn.disconnect();
			}
			if(inputStream != null) {
				inputStream.close();
			}
			if(outputStream != null) {
				outputStream.close();
			}
		}

  

posted @ 2018-06-22 17:33  馳騁衿琾  阅读(443)  评论(0编辑  收藏  举报