Steve Chambers Steve Chambers - 24 days ago 8
HTTP Question

How to avoid EOFException for an empty HTTP response from HttpURLConnection?

I'm sending an HTTP request to a server which legitimately returns a blank response with HTTP response code = 200 (OK).

But this causes the marked line below to throw an

EOFException
:

InputStream responseStream = httpURLConnection.getInputStream();
final String contentEncoding = this.connection.getContentEncoding();
if ("gzip".equalsIgnoreCase(contentEncoding)) {
responseStream = new GZIPInputStream(responseStream); // throws EOFException
}


There may be an obvious way to prevent this but I can't find it. Should I perhaps be checking something like
connection.getContentLength() > 0
or
responseStream.available() > 0
before creating the GZIPInputStream? Neither of these seem quite right and I haven't come across anything similar in example code fragments...

EJP EJP
Answer

Should I perhaps be checking something like connection.getContentLength() > 0

Yes.

or responseStream.available() > 0

Definitely not. available() == 0 isn't a valid test for EOF, and the Javadoc explicitly says so.

Comments