android is http.keepalive false necessary when using okhttp

10,149

Solution 1

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.

Solution 2

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.

Share:
10,149
joshkendrick
Author by

joshkendrick

Updated on June 14, 2022

Comments

  • joshkendrick
    joshkendrick almost 2 years

    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!

  • joshkendrick
    joshkendrick over 9 years
    some of the links i posted mention needing to do that to help with subsequent connections and calls. is that not necessary anymore?
  • IAmTheSquidward
    IAmTheSquidward over 9 years
    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.
  • Jesse Wilson
    Jesse Wilson over 9 years
    I recommended this for pre-froyo devices only. Nuke it. android-developers.blogspot.ca/2011/09/…