2

I've recently taken over an Android project. We're looking to try to speed up a sync process we have. This is in the code currently:

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

I didn't write the code, so I don't really know the reason this code was added, but ive done some googling and it seems necessary to keep connections working:

http://android-developers.blogspot.com/2011/09/androids-http-clients.html

HttpUrlConnection.openConnection fails second time

When we set this to true, the sync process speeds up substantially, but I don't want to set it to true and not have a decent idea of the consequences. Does anyone know if it's still necessary to set http.keepAlive to false? If so, for all Android devices? Is there an API level where it doesnt matter anymore?

Digging through the code history, we saw where http://square.github.io/okhttp/ was integrated. Is it still necessary to keep this setting to false when we're using OkHTTP?

Thanks!

Community
  • 1
  • 1
joshkendrick
  • 3,497
  • 8
  • 38
  • 52

2 Answers2

3

This question is rather old, but I want to point out for the sake of others that simply disabling that line is not always perfectly safe. The reason some developers do this is because the client may be talking to a server that des not correctly set the Content-Length header in the response.

If the value in the header is lower than the actual number of bytes the server sends, the extra bytes will be included as the first bytes of the response to the next request, which may make that response invalid.

Disabling keep-alive is a way to ensure that each request is self-contained, preventing errors in one response from affecting any others.

alzee
  • 1,393
  • 1
  • 10
  • 21
2

You can change that to true with no problems. http.keepAlive just tells the client that it can keep the connection to the server open, rather than renegotiating a connection every time you do something. There shouldn't be any consequences to enabling it; at least, not in my experience.

IAmTheSquidward
  • 562
  • 6
  • 22
  • some of the links i posted mention needing to do that to help with subsequent connections and calls. is that not necessary anymore? – joshkendrick Nov 18 '14 at 14:57
  • In the linked StackExchange question, that user is basically disabling keep alive as a workaround. Most HTTP connections across the web are keep alive enabled - if the server that you're connecting to supports it (which it must if you're seeing a speed boost), then there shouldn't be any issues at all. Keep alive is default `true`, so most people add your referenced line as a workaround for a poor server configuration. – IAmTheSquidward Nov 18 '14 at 15:02
  • 1
    I recommended this for pre-froyo devices only. Nuke it. http://android-developers.blogspot.ca/2011/09/androids-http-clients.html – Jesse Wilson Nov 18 '14 at 23:49