Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an accepted best-practice on making asynchronous HTTP requests in Android?

Tags:

java

android

http

I've seen any number of examples and they all seem to solve this problem differently. Basically I just want the simplest way to make the request that won't lock the main thread and is cancelable.

It also doesn't help that we have (at least) 2 HTTP libraries to choose from, java.net.* (such as HttpURLConnection) and org.apache.http.*.

Is there any consensus on what the best practice is?

like image 885
Jeremy Logan Avatar asked May 06 '09 06:05

Jeremy Logan


People also ask

Which method is used to make an asynchronous HTTP request?

Ajax. Ajax is the traditional way to make an asynchronous HTTP request. Data can be sent using the HTTP POST method and received using the HTTP GET method.

What is asynchronous request in Java?

In short, an asynchronous servlet enables an application to process incoming requests in an asynchronous fashion: A given HTTP worker thread handles an incoming request and then passes the request to another background thread which in turn will be responsible for processing the request and send the response back to the ...


1 Answers

The Android 1.5 SDK introduced a new class, AsyncTask designed to make running tasks on a background thread and communicating a result to the UI thread a little simpler. An example given in the Android Developers Blog gives the basic idea on how to use it:

public void onClick(View v) {    new DownloadImageTask().execute("http://example.com/image.png"); }  private class DownloadImageTask extends AsyncTask {    protected Bitmap doInBackground(String... urls) {       return loadImageFromNetwork(urls[0]);    }     protected void onPostExecute(Bitmap result) {       mImageView.setImageBitmap(result);    } } 

The doInBackgroundThread method is called on a separate thread (managed by a thread pooled ExecutorService) and the result is communicated to the onPostExecute method which is run on the UI thread. You can call cancel(boolean mayInterruptIfRunning) on your AsyncTask subclass to cancel a running task.

As for using the java.net or org.apache.http libraries for network access, it's up to you. I've found the java.net libraries to be quiet pleasant to use when simply trying to issue a GET and read the result. The org.apache.http libraries will allow you to do almost anything you want with HTTP, but they can be a little more difficult to use and I found them not to perform as well (on Android) for simple GET requests.

like image 120
jargonjustin Avatar answered Sep 22 '22 19:09

jargonjustin