HttpURLConnection: What's the deal with having to read the whole response?

Posted by stormin986 on Stack Overflow See other posts from Stack Overflow or by stormin986
Published on 2010-05-08T03:32:08Z Indexed on 2010/05/08 3:38 UTC
Read the original article Hit count: 349

Filed under:
|
|

My current problem is very similar to this one.

I have a downloadFile(URL) function that creates a new HttpURLConnection, opens it, reads it, returns the results. When I call this function on the same URL multiple times, the second time around it almost always returns a response code of -1 (But throws no exception!!!).

The top answer in that question is very helpful, but there are a few things I'm trying to understand.

So, if setting http.keepAlive to false solves the problem, it indicates what exactly? That the server is responding in a way that violates the http protocol? Or more likely, my code is violating the protocol in some way? What will the trace tell me? What should I look for?

And what's the deal with this:

You need to read everything from error stream. Otherwise, it's going to confuse next connection and that's the cause of -1.

Does this mean if the response is some type of error (which would be what response code(s)?), the stream HAS to be fully read? Also, every time I am attempting an http request I am basically creating a new connection, and then disconnect()ing it at the end.

However, in my case I'm not getting a 401 or whatever. It's always a 200. But my second connection almost always fails. Does this mean there's some other data I should be reading that I'm not (in a similar manner that the error stream must be fully read)?

Please help shed some light on this? I feel like there's some fundamental http protocol understanding I'm missing.

© Stack Overflow or respective owner

Related posts about android

Related posts about java