How to set content length as long value in http header in java?

后端 未结 4 679
执念已碎
执念已碎 2021-01-01 22:48

I am writing a web server in java that is transferring file upto 2GB fine. When I searched for the reason, I found like java HttpServelet only allows us to set the content l

相关标签:
4条回答
  • 2021-01-01 23:00

    You can also use below sample code.

    long length = fileObj.length();
    
    if (length <= Integer.MAX_VALUE)
    {
      response.setContentLength((int)length);
    }
    else
    {
      response.addHeader("Content-Length", Long.toString(length));
    }
    
    0 讨论(0)
  • 2021-01-01 23:03

    Try this:

    long length = ...;
    response.setHeader("Content-Length", String.valueOf(length))
    

    Hope this helps...

    0 讨论(0)
  • 2021-01-01 23:09

    Do not set it and use chunked encoding. Also beware of HEAD requests = these requests should return the same content-length as GET, but not sending the actual body. Default implementation of HEAD in javax.servlet.http.HttpServlet is done by calling GET on the same URL and ignoring all the response body written (only counting characters) - see the following fragment:

    protected void doHead(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        NoBodyResponse response = new NoBodyResponse(resp); // mock response (not writing)
        doGet(req, response); // performs a normal GET request
        response.setContentLength(); // this uses INTEGER counter only
    }
    

    The problem is that the content length counter is also integer. So I recommend overloading doHead method also and not setting the content length at all (you might want to leave GET call also to save time generating the giant file).

    0 讨论(0)
  • 2021-01-01 23:15

    Don't set it at all.

    Just let it use chunked transfer mode, which is the default. There is no Content-Length header in that circumstance. See @BalusC's comment under this question.

    0 讨论(0)
提交回复
热议问题