我正在制作一个简单的 Javacom.sun.net.httpserver.HttpServer来提供静态视频文件。如果我返回状态代码 206,部分内容,当我尝试通过浏览器访问它时,视频无法播放(状态代码为 200 的视频播放正常,但我希望能够搜索和循环播放视频),这是我的HttpHandler:
final String path = StaticHandler.toPathSafe(httpExchange.getRequestURI().getPath());
System.out.println(path);
final File file = new File(path);
if (file.isFile())
{
int code = 200;
long position = 0L;
long end = file.length();
if (httpExchange.getRequestHeaders().containsKey("Range"))
{
try
{
long[] range = StaticHandler.parseRange(httpExchange.getRequestHeaders().get("Range").get(0));
position = range[0];
if (range[1] != -1)
end = range[1];
// the video loads fine when code = 200;
code = 206;
httpExchange.getResponseHeaders().set("Content-Range", "bytes " + position + "-" + end + "/" + file.length());
}
catch (Exception e)
{
e.printStackTrace();
}
}
httpExchange.getResponseHeaders().set("Accept-Range", "bytes");
httpExchange.getResponseHeaders().set("Content-Type", "video/mp4");
httpExchange.getResponseHeaders().set("Content-Length", String.valueOf(end - position));
System.out.println("Response: " + position + ", " + end);
httpExchange.sendResponseHeaders(code, 0L);
final FileChannel fileChannel = new FileInputStream(file).getChannel();
final WritableByteChannel responseChannel = Channels.newChannel(response.getOutputStream());
fileChannel.transferTo(position, end - position, responseChannel);
responseChannel.close();
fileChannel.close();
}
else
{
System.out.println("404");
httpExchange.sendResponseHeaders(404, -1);
}
上面的代码无法在 chrome 上加载,但在 firefox 中工作正常,这是我在 Chrome 中获得的标头:
Response Headers:
Accept-range: bytes
Content-length: 31491166
Content-range: bytes 0-31491166/31491166
Content-type: video/mp4
Date: Sat, 27 Jul 2019 14:32:55 GMT
Transfer-encoding: chunked
我是否遗漏了什么和/或我的代码有什么问题?
杨魅力
噜噜哒
相关分类