Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How should I handle server timeouts and error code responses to an http post in Android App?

My Android App does http posts to URLs like http://example.com/[email protected] So the Android App basically talks to PHPs on the server side and receives JSON responses and parses them to populate various views in the App. Works fine.

My question is- How should I handle events below in the Android App so that in case these events occur in the server side application, the App should not FORCE CLOSE as it does now.

  1. Server Time out occurs and no response is received. The App force closes now. I want to handle this appropriately.

  2. Error Codes returned as a response to the App http post to the server. The App Force closes currently since I have not handled this.

I have encountered these two scenarios where the App is not coded to handle these events. Please feel free to add any other events that might occur that might lead ANRs occur in Android App.

A little code snippet or clue will help me a lot since I have never done this before.

Thanks.

like image 212
Aakash Avatar asked May 09 '11 19:05

Aakash


1 Answers

Adding to the very good suggestions so far...

My work associate taught me to use classes from the org.apache.http package like this:

String result = null;
HttpGet request = new HttpGet(some_uri);

// As Jeff Sharkey does in the android-sky example, 
// use request.setHeader to optionally set the User-Agent header.

HttpParams httpParams = new BasicHttpParams();
int some_reasonable_timeout = (int) (30 * DateUtils.SECOND_IN_MILLIS);
HttpConnectionParams.setConnectionTimeout(httpParams, some_reasonable_timeout);
HttpConnectionParams.setSoTimeout(httpParams, some_reasonable_timeout);
HttpClient client = new DefaultHttpClient(httpParams);

try
{
  HttpResponse response = client.execute(request);
  StatusLine status = response.getStatusLine();
  if (status.getStatusCode() == HttpStatus.SC_OK)
  {
    ResponseHandler<String> responseHandler = new BasicResponseHandler();
    result = responseHandler.handleResponse(response);
  }
  else
  {
    // Do something else, if wanted.
  }
}
catch (ClientProtocolException e)
{
  Log.e(LOG_TAG, "HTTP Error", e);
  // Do something else, if wanted.
}
catch (IOException e)
{
  Log.e(LOG_TAG, "Connection Error", e);
  // Do something else, if wanted.
}
finally
{
  client.getConnectionManager().shutdown();
}

// Further parse result, which may well be JSON.
like image 106
Thane Anthem Avatar answered Sep 21 '22 13:09

Thane Anthem