Java通过http方式下载文件

	@GetMapping("getFile/v1.1")
	public void getFileV2(HttpServletResponse response) throws Exception {
	//设置请求头,表示下载文件和文件名称
		response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("xx.jpg", "utf-8"));
		String urlStr = "https://dn-odum9helk.qbox.me/Fvzr5I55m4wJYsXkTrUlqXIyhdl0";
		URL url = new URL(urlStr);
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		// 设置超时间为3秒
		conn.setConnectTimeout(3 * 1000);
		//获取输入流
		InputStream inputStream = conn.getInputStream();
		//获取输出流
		ServletOutputStream outputStream = response.getOutputStream();
		//每次下载1024位
		byte[] b =new byte[1024];
		int len = -1;
		while((len = inputStream.read(b))!=-1) {
			outputStream.write(b, 0, len);
		}
		inputStream.close();
		fileOutputStream.close();
	}

你可能感兴趣的:(SpringBoot,java,http,web,spring,boot)