Search code examples
androidjsonhttpurlconnectionkeep-alivehttpconnection

Android: first http response always takes longer (even without keep-alive)


I am using the class HttpUrlConnection for requesting JSON responses

I realized that no matter if I set or not

System.setProperty("http.keepAlive", "false");

The first response is always going to take longer, while the next responses are very quick, with and without keepAlive. I am not even using SSL.

Notice that, my app doesn't need to perform any authentication with the server, so there isn't any startup call to the webservices. The first request I make to the webservices is actually the very first.

I am also verifying server-side with "netstat", that by setting keepAlive false on the Android client the connections disappear straight away, while without specifying keepAlive false they keep staying as "ESTABLISHED".

How can you explain that subsequent responses are quicker even if the connection doesn't persist?

ANDROID CODE:

line 1) URL url = new URL(stringUrl);
line 2) HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
line 3) InputStream instream = new BufferedInputStream(urlConnection.getInputStream());

Until line 2 everything always gets executed very quickly, either with keepAlive or not. Line 3 in the first request takes around 3 seconds, while in all subsequent always less than 1 second. Each request is about 0.5KB gzipped.

SYSTEM:

  • I am testing using a Nexus 5, connected via 3G
  • My webservices are written in Go, running on a CentOS 6.4 linux server
  • I am using standard tcp v4

UPDATE:

For the moment I have decided to use a trick: when the fragment is resuming, I make a HTTP HEAD request to the server. In this way all subsequent calls in the next 10 seconds are very quick. If the user waits more than 10 seconds then the first one will be slow, and the next ones will be quick again. This is all happening without using KeepAlive.

It's a really big mistery now. It looks like there is some kind of "awake" period which lasts for about 10 seconds. I don't think there is anything strange on my code which can result on that. Also because everything seems to happen during the line 3 I reported above.

SOLVED! thanks to Mark Allison!

Here is a very clear explanation: http://developer.android.com/training/efficient-downloads/efficient-network-access.html

Also, everything can easily be monitored using Android DDMS's Network Statistics. If you wait some seconds (let's say 20) from last request, you can see that it takes 2 seconds to transmit a new request.


Solution

  • I suspect that the lag that you are seeing is simply down to the cellular radio transitioning from either low power or idle state to full power (which can take over 2 seconds).

    Check out Reto Meier's excellent DevBytes series on Efficient Data Transfer for an in-depth explanation of what's going on.