java 获取资源返回流数据


	/**
	 * 获取资源 (mp3)
	 * @param file 文件路径
	 * @param response 响应
	 */
	@RequestMapping(value="getResource")
	public @ResponseBody void getResource(String file, HttpServletResponse response){
		try{
			//输出 mp3 IO流
			response.setHeader("Content-Type", "audio/mp3");
			File fileTemp = new File(new String((file).getBytes("iso-8859-1"),"utf-8"));         
			// 这里传过来相对路径,自行拼接路径
			int len_l = (int) fileTemp.length();
			byte[] buf = new byte[2048];
			FileInputStream fis = new FileInputStream(fileTemp);
			OutputStream out = response.getOutputStream();
			len_l = fis.read(buf);
			while (len_l != -1) {
				out.write(buf, 0, len_l);
				len_l = fis.read(buf);
			}
			out.flush();
			out.close();
			fis.close();
		}catch (Exception e){
			System.out.println(e);
		}
	}

	/**
	 * 获取资源 Http(mp3)
	 * @param url 网络路径
	 * @param response 响应
	 */
	@RequestMapping(value="getHttpResource")
	public @ResponseBody void getHttpResource(String url, HttpServletResponse response){
		try{
			//输出 mp3 IO流
			url = new String(new String((url).getBytes("iso-8859-1"),"utf-8"));
			response.setHeader("Content-Type", "audio/mp3");
			HttpURLConnection httpConn = (HttpURLConnection) new URL(url).openConnection();
			httpConn.setDoOutput(true);// 使用 URL 连接进行输出
			httpConn.setDoInput(true);// 使用 URL 连接进行输入
			httpConn.setUseCaches(false);// 忽略缓存
			httpConn.setRequestMethod("GET");// 设置URL请求方法
			//可设置请求头
			httpConn.setRequestProperty("Content-Type", "application/octet-stream");
			httpConn.setRequestProperty("Connection", "Keep-Alive");// 维持长连接
			httpConn.setRequestProperty("Charset", "UTF-8");
			//可设置请求头
			InputStream in = httpConn.getInputStream();
			OutputStream out = response.getOutputStream();

			byte[] bs = new byte[2048];
			int count = 0;
			while (-1 != (count = in.read(bs, 0, bs.length)))
				out.write(bs, 0, count);
			out.flush();
			out.close();
			in.close();
		}catch (Exception e){
			System.out.println(e);
		}
	}

 

你可能感兴趣的:(Java)