Saturday, 19 November 2011

Android - HttpUrlConnection - disconnect completely

HttpUrlConnection is a class of Android that enable the connection from the mobile device to any server based on a URL address.

This class offers both methods to connect and to disconnect once the url address is set. They are:
  • connect()
  • disconnect()
Because we are talking about http connections over mobile devices, which could be an expensive operation, there is something called "Connection pool", where even when the method disconnect() is called, the connection keeps alive in this pool

The problem could appears when the user switch from one interface to another one, from Wifi to Mobile network or from Mobile to Wifi and she still want to connect to the previous server. At this point, the connection won't be stablished because it hasn't been disconnected completely, making the connection pending until it is killed by the system.

To avoid this problem, the follow setting for the system could be used:

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

This code should be added before the connection has been stablished. Then, once the disconnect method is called, the mobile device will be disconnected to the server completely and new connection through a new interface to the same server could be stablished.

Sample code:
System.setProperty("http.keepAlive", "false");
HttpURLConnection conn = (HttpURLConnection) mURL.openConnection();
conn.connect();
....
conn.disconnect()

Source: StackOverFlow: http://stackoverflow.com/questions/3352424/httpurlconnection-openconnection-fails-second-time
For more information:

1 comment: