Cancel AsyncTask when HTTPPost fails?
I'm trying to cancel my AsyncTask when connecting to the server fails. I tried cancel()
, but the onPostExecute()
method still gets called, instead of onCancelled()
.
This is what I have inside doInBackground()
:
protected String doInBackground(String... params) {
Log.i("ping", "doInBackground() started");
DefaultHttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(), 15000);
HttpResponse response;
HttpEntity entity;
try {
HttpPost post = new HttpPost("http://192.168.1.6/ping/login.php");
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
nvps.add(new BasicNameValuePair("username", getEmail()));
nvps.add(new BasicNameValuePair("password", getPassword()));
post.setHeader("Content-Type", "application/x-www-form-urlencoded");
post.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
response = client.execute(post);
entity = response.getEntity();
InputStream iStream = entity.getContent();
read(iStream);
iStream.close();
if(entity != null)
entity.consumeContent();
Log.i("ping", "doInBackground() vervolgd");
} catch (Exception e) {
e.printStackTrace();
Log.e("tvsping", "Exception: " + e.getMessage());
cancel(true);
}
return null;
}
I'm trying to see what happens when the server can't be reac开发者_开发技巧hed (I'm shutting it down, so there's no way my phone is getting any response) and I get IOException: the connection was reset
.
Any ideas how I should check if the connection isn't made?
update I solved this like Tanmay suggested, with a boolean. But I have another problem: Every time doInBackground() is called it takes about three minutes to stop, when it can't find the servers. Everything is fine when it can reach the server, but I can't have this taking 3 minutes before the user is notified of anything (I could do a background process, but still a 3 minute wating bar is no good neither)
Any ideas what is wrong with my code? This can't be normal, right?
From doInBackground()
method you are returning a String
.You can return null
if your HTTPPost
fails.And then in onPostExecute()
method just check what are you getting, if the String
is null dont do anything which you really want and on successful running do your UI work
Hope this will help you.
HttpHost target = new HttpHost("192.168.2.3", 80);
HttpPost post = new HttpPost("/ping/login.php");
response = client.execute(target, post);
This solved the slow server response for me.
精彩评论