I have an application which connects to a web service. I can connect to the web service any number of times without any problem using WIFI or 3G provided that I stay loyal to my connection type during the life cycle of my application. That is if I don't switch from WIFI to 3G. If I switches from WIFI to 3G, I can't get a response anymore. My connection just keeps on waiting for response.
I tried 4 scenarios below. I'm only having problem with the 3rd scenario. What could be the problem?
1st Scenario: Connection is always on WIFI (Ok)
2nd Scenario: Connection is always on 3G (Ok)
3rd Scenario: Connection switches from WIFI to 3G (No response)
getResponseCode
was called.4th Scenario: Connection switches from 3G to WIFI (Ok)
My guess is by default, HttpURLConnection
thinks WIFI as a better connection type compare to 3G. So when the connection is switched from WIFI to 3G, HttpURLConnection
refuses to acknowledge 3G and still tries to connect using WIFI. On the other hand, HttpURLConnection
allows switching from 3G to WIFI since WIFI is a better connection type. Am I correct with this? If so, how do I allow switching from WIFI to 3G?
Below is a snippet of my code: (I call it every time I connect to a web service.)
//open new connection
httpsURLConnection = (HttpURLConnection) ((new URL(url)).openConnection());
httpsURLConnection.setDoInput(isDoInput);
httpsURLConnection.setDoOutput(isDoOutput);
try
{
//supply parameters
OutputStreamWriter wr = new OutputStreamWriter(httpsURLConnection.getOutputStream());
wr.write(data);
wr.flush();
if(httpURLConnection != null)
{
if (httpsURLConnection.getResponseCode() == HttpsURLConnection.HTTP_OK) //connection hangs here
{
//some code
}
else
{
//some code
}
}
}catch(Exception e)
{
}
I'm not sure why but adding System.setProperty("http.keepAlive", "false")
on the code solves the problem.
According to the Android Developers Blog (androids-http-clients), HttpURLConnection
has a bug prior to Froyo and it can be solved by disabling connection pooling just like above. However, I'm using Gingerbread so I'm not sure why HttpURLConnection is still misbehaving on my application.
To others: If you can provide more explanation, please don't hesitate to edit my post.