Pavel Zdarov
Pavel Zdarov

Reputation: 2347

How to process HttpResponse in AsyncTask android

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 ?

Upvotes: 2

Views: 1873

Answers (1)

Ted Hopp
Ted Hopp

Reputation: 234857

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
}

Upvotes: 3

Related Questions