Best way to configure HTTP header content-length
Hello,
I have a video player that makes a request via Servlet that already works and I need to include a new video.
At first I will return the video according to the logged in user.
The problem I came across is that the videos are of different sizes and the response header has a pre-defined content-Length setting that I believe is from the video that already exists:
response.setHeader("Content-Length", "15800000");
I researched about the header properties and I did not understand if it is valid to omit this value or try to somehow schedule the change of this response header.
This is the Servlet:
public void doGet(HttpServletRequest request,HttpServletResponse response) throws IOException {
try (FileInputStream fin = new FileInputStream(FileServerUtil.getFileServer()
+ PASTA_MEDIA + File.separator + NOME_ARQUIVO);
ServletOutputStream out = response.getOutputStream()) {
response.setContentType("video/mp4");
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("accept-ranges", "bytes");
response.setHeader("cache-control", "public,max-age=14400,public");
response.setHeader("Content-Length", "15800000");
byte [] buf = new byte[4096];
int read;
while((read = fin.read(buf)) != -1) {
out.write(buf, 0, read);
}
} catch (Exception e) {
logger.error(e);
}
}
I could put an if else and change the header according to the video but I believe it would be a "dumb" way to do it. I would like a suggestion on this!
1 answers
I ended up changing my FileInputStream
to RandomAccessFile
, so I can use the method
length()
, I don't know if it would be a good approach but now I can get the file size in bytes to include in the header.