The response code isn't available until after you've sent the content.
By asking for the response code before you send the content, you're forcing HttpUrlConnection to terminate the request to force the server to send one. Don't ask for the response until after your request is complete.
One question, though: why is Http set up that way so that even if you aren't allowed to write to a stream, you still have to wait till after spending all that processing time writing out the bytes of a file before you can find that out?
author and iconoclast
Well, HTTP was designed as a very simple request/response protocol. So the client sends everything they're going to send, and then the server sends everything they're going to send. Originally, that was always done in a separate network connection -- i.e., one request, one response per connection, by definition. This makes it possible for the client to be completely "dumb" -- a request can come out of a file, and a response go into a file, without the client doing any interpretation whatsoever.