HttpURLConnection, problem turning on/off WiFi and trying to connect
I have an application which is a RESTful API consumer, and I wish to have a timeout on my connection with the API.
As I've searched, and also tested, the HttpURLConnection.setReadTimeout() method doesn't work, so the solution I found was to use an AsyncTask which will try to connect to the server and then pass the timeout to the AsyncTask.get().
It works, partially. The problem is when I do the following:
- Enter the application with the WiFi turned on. I click "Login" button and get "Invalid/User password". Ok.
- Turn off the WiFi, click "Login" button. The application tries to connect but after 5 seconds (the timeout I chose) it shows me the notification dialog saying I'm not connected. Ok, everything as expected.
- Turn on back the WiFi, click "Login" button. It st开发者_如何学运维ills working as if I was not connected, always showing the dialog. I can wait many seconds but the behaviour is the same as If I was disconnected.
I debugged all my code, step by step using Eclipse and there's nothing wrong with the logic. My HttpURLConnection is always a new object, so I'm not trying to use the same connection object to connect after the WiFi is turned on back... Also I'm using the Scribe library, for OAuth, but I checked the source code and everything seems ok, except that I changed the method which creates a connection to always use a new instance.
I'm starting to think that Android is "caching" my connection object or the AsyncTask object...
Below some code of my RequestManager class:
public class RequestManager {
private static RequestManager self = new RequestManager();
private Request currentRequest;
private static final long TIMEOUT = 5000;
public static RequestManager getInstance() {
return self;
}
public void startRequest(Request request) {
if (currentRequest != null) return;
currentRequest = request;
}
public String getResponse() throws ConnectionErrorException {
RequestThreat rt = new RequestThread();
rt.execute(currentRequest);
try {
return (String) rt.get(TIMEOUT, TimeUnit.MILISECONDS);
} catch (InterruptedException e) {
} catch (ExecutionException e) {
} catch (TimeoutException e) {
throw new ConnectionErrorException();
} finally {
endRequest();
}
return null;
}
public void endRequest() {
currentRequest = null;
}
private class RequestThread extends AsyncTask<Request, Integer, String> {
@Override
protected String doInBackground(Request... requestParams) {
return requestParams[0].send().getBody();
}
}
}
Also in the method I call getResponse()
I'm calling endRequest()
after.
Any thoughts?
You should check to see if a network connection is available before trying to access the network. Have a look at this quesion:
- How to respect network use settings
Specifically:
NetworkInfo networkInfo = cm.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isAvailable() && networkInfo.isConnected()) {
精彩评论