0

I'm using Android Asynchronous Http Client .

Which one is true: to create one AsyncHttpClient for each request, or to create one client for all requests.

Now I have one Singltone RequestHelper like this:

private RequestHelper() {
    mContext = MyApplication.getContext();
    baseUrl = mContext.getString(R.string.base_url);
}

public static RequestHelper getInstance() {
    if (instance == null) {
        instance = new RequestHelper();
    }
    return instance;
}


public void performLoginRequest(String username, String password, GsonHttpResponseHandler gsonHttpResponseHandler) {
    AsyncHttpClient client = new AsyncHttpClient();
    attachHeaders(client);
    client.post(mContext, baseUrl + "/login", null, "application/json", gsonHttpResponseHandler);
}

public void getCountries(GsonHttpResponseHandler gsonHttpResponseHandler) {
    AsyncHttpClient client = new AsyncHttpClient();
    client.get(mContext, baseUrl + "/countries", null, gsonHttpResponseHandler);
}

You can see that now I'm creating AsyncHttpClient object for every request

hhs
  • 716
  • 1
  • 6
  • 22
  • If you use a different client for each request, you won't be able to use cookies properly. Check http://stackoverflow.com/questions/3587254/how-do-i-manage-cookies-with-httpclient-in-android-and-or-java – Gordak Jul 08 '15 at 09:10

2 Answers2

0

I think creating one Asynctask for each request is better for code review. I think both can be done if you manage each case and give the right input to the AsyncTask to let it know which function it needs to execute, But you might end with a 2000 lines class instead of 10 class of 200 lines with explicit class name, so anytime you would need to change something you might need to check the whole 2000 lines and after changing something you would need to be sure you didn't break anything in the class. But this is just a matter of opinions.

Bxtr
  • 316
  • 1
  • 13
0

From this example found on your source link, it is okay to create one client for all requests. You can used it multiple.

import com.loopj.android.http.*;

public class TwitterRestClient {
  private static final String BASE_URL = "http://api.twitter.com/1/";

  private static AsyncHttpClient client = new AsyncHttpClient();

  public static void get(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
      client.get(getAbsoluteUrl(url), params, responseHandler);
  }

  public static void post(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
      client.post(getAbsoluteUrl(url), params, responseHandler);
  }

  private static String getAbsoluteUrl(String relativeUrl) {
      return BASE_URL + relativeUrl;
  }
}

Therefore, the answer is to create one client for all requests.