2

My activity executes http request using AsynTask. How to process HttpResponse in case if web-server does not answer? Currently when my web-server is down, AsynTask just stopped at "HttpResponse response = client.execute(httppost);" and then do nothing. I need to process this response and do something, but code belowe "execute" is not executed.

Here is ny background task:

 protected String doInBackground(String... params) { HttpClient client = new DefaultHttpClient(); String result = null; try { // Add your data List<NameValuePair> postData = new ArrayList<NameValuePair>(2); postData.add(new BasicNameValuePair("session_id", session_id)); postData.add(new BasicNameValuePair("i_key", params[0])); HttpPost httppost = new HttpPost( "http://my.webserver.com/getInfo.php"); httppost.setEntity(new UrlEncodedFormEntity(postData)); HttpResponse response = client.execute(httppost); HttpEntity responseEntity = response.getEntity(); if (responseEntity != null) { BufferedReader reader = new BufferedReader( new InputStreamReader(responseEntity.getContent(), "UTF-8")); result = reader.readLine().toString(); } else { Toast.makeText(this, "DDDDDDD",Toast.LENGTH_LONG).show(); } } catch (IllegalArgumentException e1) { e1.printStackTrace(); } catch (IOException e2) { e2.printStackTrace(); } return result; } 

How I can handle response if web-server is down and not reply ?

3
  • Did you get timeout exception after 1 minute? Commented Apr 21, 2013 at 17:05
  • Put a timeout, after that you will get a timeout exception, if you web-server is not down/don't reply. Give it a try, stackoverflow.com/questions/16098810/… Commented Apr 21, 2013 at 17:10
  • You should'nt use AsyncTask to perform network request since when the orientation of your device changes the activity is destroyed but also the AsyncTask which is tied to the lifecycle of this activity. To avoid that you should use Service pattern instead. Commented Apr 24, 2013 at 19:43

1 Answer 1

3

You need to set a timeout for your client's connection. For instance:

protected String doInBackground(String... params) { HttpParams httpParameters = new BasicHttpParams(); // set the connection timeout and socket timeout parameters (milliseconds) HttpConnectionParams.setConnectionTimeout(httpParameters, 5000); HttpConnectionParams.setSoTimeout(httpParameters, 5000); HttpClient client = new DefaultHttpClient(httpParameters); . . . // the rest of your code } 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.