Search code examples
javaandroidinputstreamhttpurlconnectionbufferedinputstream

HttpUrlConnection gets response body on connect()


Consider the following code.

try {
    httpURLConnection = (HttpURLConnection) new URL(strings[0]).openConnection();

    httpURLConnection.setConnectTimeout(Config.HTTP_CONNECTION_TIMEOUT);
    httpURLConnection.setReadTimeout(Config.HTTP_CONNECTION_TIMEOUT);

    httpURLConnection.connect();

    responseCode = httpURLConnection.getResponseCode();
    httpURLConnection.getHeaderFields();
}
finally {
    httpURLConnection.disconnect();
}

The issue is even when I don't use the InputStream to read the response, in my Internet/Wifi connection logs I can see the response-body. What I want is simply to check a field in the header and based upon that field I will continue reading the InputStream.

My questions are these:

  1. Is it correct behavior for the connected stream to automatically download all/partial file even before a BufferedInputStream is created and read from?
  2. If yes, then is it possible to stop the file download until an InputStream is used to read the response?
  3. If not then is there something I am doing wrong or missing?

Solution

    1. The response includes both the header and the body, the server does not stop for the client to acknowledge the headers before sending the body.
      At the time the client is able to read the response code from the headers, a part of the body has already been sent, the size of which depends on the network latency, buffering, ....
      The current implementation of HttpURLConnection.getResponseCode() even use getInputStream() to ensure that the connection is in the correct state.

    2. The client can choose to ignore the body, but it's usually not recommended, because it may prevent a persistent connection to be reused.
      I am not sure about Android but since Java 6, a background thread is automatically used to read the remaining data.

    3. If If-Modified-Since is not an option, why not use a HEAD request ? :

    The HTTP HEAD method requests the headers that are returned if the specified resource would be requested with an HTTP GET method. Such a request can be done before deciding to download a large resource to save bandwidth, for example.