Best way to set up the HTTP header content-length

Asked

Viewed 191 times

0

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 Response header has a pre-defined Content-Length configuration that I believe is the video that already exists:

response.setHeader("Content-Length", "15800000");

I searched the header properties and did not understand if it is valid to omit this value or try to program in any way 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 Else and change the header according to the video but I believe it would be a "dumb" way to do. I would like a suggestion on that!

1 answer

-2


I ended up changing mine FileInputStream for RandomAccessFile, so that you 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.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.