Why do I get the error java.lang.IllegalStateException: Header already sent ?

Nils Kulk

Hi, sounds like you're trying to set a header after you've written something to the response output stream.

An HTTP repsonse message is composed as follows: an HTTP reponse code (something like "HTTP/1.1 200 OK") followed by zero or more headers (something like "ContentType: text/html") followed by the repsonse contents.

This allows a server to send the headers to the client before sending the response contents. This way the client can determine some meta data about the repsonse (for example what the type of the content is).

This means that as soon as the first byte of repsonse contents is written the reponse goes into a state where headers can't be set. Trying to do so, results in an IllegalStateException.

So the wrong way is:

OutputStream out =
   response.getOutputStream();
out.writeln("Hello...");
out.flush();
response.setContentType("text/html");

The right way is:

response.setContentType("text/html");
OutputStream out =
   response.getOutputStream();
out.writeln("Hello...");
out.flush();
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.