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; } } }
兄弟,我们是智能家居公司,有个流媒体服务器的项目外包。能否交流一下?我的QQ718140459,TEL13911017746,我在北京。
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。