Can we run HttpClient many times in AsyncTask?

Ask by : Edward Sullen November 04, 2012 09:22

Due to android doc , The task can be executed only once.

I'm trying to run HttpClient in UI-Thread. But it allows for the only once. If I want to get another data from another link which is not yet run at the first start, how can I do it? Until I get all data when the app starts for the first time, it takes long time. Is there anyone who knows how to solve this problem ?

View original question

Answer by : Anup CowkurNovember 04, 2012 09:13

You're running a network operation on main thread. Use async task to run network operations in background thread (do your http requests in a background thread).

Do your networking in an async task like this:

class WebRequestTask extends AsyncTask{

    protected void onPreExecute() {
    //show a progress dialog to the user or something

    protected void doInBackground() {
        //Do your networking here

    protected void onPostExecute() {
        //do something with your 
       // response and dismiss the progress dialog

  new WebRequestTask().execute();

Here are some tutorials for you if you don't know how to use async tasks:

Here are the official docs from Google:

You can call the async task multiple times whenever needed to perform the download tasks. You can pass parameters to the async task so that you can specify what data it should download (for example by passing a different url each time as a parameter to the async task). In this way, using a modular approach, you can call the same aync task multiple times with different parameters to download the data. The UI thread wont be blocked so the user experience will not be hindered and your code will be thread safe too.

View original answer