Friday 14 October 2011

Android: creating an aynchronous task to make a http request

What we'll do to make an aynchronous http request is extend the AsyncTask class (overriding the doInBackground(...) and onPostExecute(...) methods) as follows...

public class MyAsyncTask extends AsyncTask<HttpRequestBase, Void, HttpResponse>
{
 @Override
 protected HttpResponse doInBackground(HttpRequestBase... httpRequests)
 {
  DefaultHttpClient httpClient = new DefaultHttpClient();
  HttpResponse response = httpClient.execute(httpRequests[0]);
  return response;
 }
 @Override
 protected void onPostExecute(HttpResponse httpResponse)
 {
  // handle response
 }
}

... and then instantiate the new MyAsyncTask class and call its execute(...) method passing in a HttpRequestBase instance as a parameter to make a http request. We could make this MyAsyncTask class smarter, constructing it with a DefaultHttpClient instance instead of creating a DefaultHttpClient instance in the doInBackground(...) method, or constructing the MyAsyncTask class additionally with a handler that reports back completion of the http request in the onPostExecute(...) method, or making changes to allow multiple simultaneous http requests to be dispatched. Hopefully though the above serves as a bare bones example to explain the general concept and to get you started.

No comments: