Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

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 length as int. As the maximum size of integer is 2GB, its working fine upto 2gb when I am using response.setContentLength method. Now the problem is bydefault response.setContentLength has the parameter of integer. So it is not taking long value as parameter. I have already tried response.setHeader("Content-Length", Long.toString(f.length())); response.addHeader("Content-Length", Long.toString(f.length())); but nothing is working. All time it is failing to add content length when it is a long value. So please give any working solution for HTTPServletResponse so that I can set the content length as long value.

like image 587
Ghosh Avatar asked Jul 13 '12 08:07

Ghosh


People also ask

How do I change the Content Length of an HTTP header?

To manually pass the Content-Length header, you need to add the Content-Length: [length] and Content-Type: [mime type] headers to your request, which describe the size and type of data in the body of the POST request.

How do I get the Content Length of a HTTP header?

To check this Content-Length in action go to Inspect Element -> Network check the request header for Content-Length like below, Content-Length is highlighted.

Is Content Length required header?

The Content-Length header is mandatory for messages with entity bodies, unless the message is transported using chunked encoding. Content-Length is needed to detect premature message truncation when servers crash and to properly segment messages that share a persistent connection.

Is Content Length header in bytes?

The Content-Length header indicates the size of the message body, in bytes, sent to the recipient.


2 Answers

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));
}
like image 153
LJRKUMAR Avatar answered Oct 08 '22 22:10

LJRKUMAR


Try this:

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

Hope this helps...

like image 34
Yuriy Nakonechnyy Avatar answered Oct 08 '22 21:10

Yuriy Nakonechnyy