开发者社区> 问答> 正文

html5播放java后台返回视频流? 报错

html5播放java后台返回视频流? 400 报错

由于公司要求视频播放需要对链接进行认证,所以我想在java代码中处理请求,然后再把视频流写回客户端。

但是页面使用的video标签始终不能播放。如果这种方案不行,那么还有其他的解决方案吗?

以下是我返回流的代码:

private void processRequest(final HttpServletRequest request,
			final HttpServletResponse response) throws IOException {

		// String videoFilename =
		// URLDecoder.decode(request.getParameter("video"), "UTF-8");
		String videoFilename = "20150121_130906.mp4";
		Path video = Paths.get(videoPath, videoFilename);

		int length = (int) Files.size(video);
		LogUtil.paramAndResultLocal("--processRequest-", "length-" + length, "");
		int start = 0;
		int end = length - 1;

		String range = request.getHeader("Range");
		Matcher matcher = RANGE_PATTERN.matcher(range);

		if (matcher.matches()) {
			String startGroup = matcher.group("start");
			start = startGroup.isEmpty() ? start : Integer.valueOf(startGroup);
			start = start < 0 ? 0 : start;

			String endGroup = matcher.group("end");
			end = endGroup.isEmpty() ? end : Integer.valueOf(endGroup);
			end = end > length - 1 ? length - 1 : end;
		}

		int contentLength = end - start + 1;
		LogUtil.paramAndResultLocal("--processRequest-", "start-" + start,
				"-end-" + end);
		response.reset();
		response.setBufferSize(BUFFER_LENGTH);
		response.setHeader("Content-Disposition",
				String.format("inline;filename=\"%s\"", videoFilename));
		response.setHeader("Accept-Ranges", "bytes");
		// response.setDateHeader("Last-Modified",
		// Files.getLastModifiedTime(video).toMillis());
		// response.setDateHeader("Expires", System.currentTimeMillis() +
		// EXPIRE_TIME);
		// LogUtil.paramAndResultLocal("--processRequest-",
		// "probeContentType-"+Files.probeContentType(video), "");
		response.setContentType(Files.probeContentType(video));
		response.setHeader("Content-Range",
				String.format("bytes %s-%s/%s", start, end, length));
		response.setHeader("Content-Length", String.format("%s", contentLength));
		response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT);

		int bytesRead;
		int bytesLeft = contentLength;
		ByteBuffer buffer = ByteBuffer.allocate(BUFFER_LENGTH);

		try (SeekableByteChannel input = Files.newByteChannel(video, READ);
				OutputStream output = response.getOutputStream()) {

			input.position(start);

			while ((bytesRead = input.read(buffer)) != -1 && bytesLeft > 0) {
				buffer.clear();
				output.write(buffer.array(), 0,
						bytesLeft < bytesRead ? bytesLeft : bytesRead);
				bytesLeft -= bytesRead;
			}
		}
	}



展开
收起
优选2 2020-06-04 18:05:48 1412 0
1 条回答
写回答
取消 提交回答
  • 兄弟,我们是智能家居公司,有个流媒体服务器的项目外包。能否交流一下?我的QQ718140459,TEL13911017746,我在北京。

    2020-06-05 13:12:18
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
从《阿里巴巴Java开发手册》编写推广谈技术成长 立即下载
如何通过 Serverless 提高 Java 微服务治理效 立即下载
天猫HTML5互动技术实践 立即下载