简体   繁体   中英

Getting response out of AsyncHttpClient

Im using this lib: http://loopj.com/android-async-http/ to make all my requests && The biggest thing currently making my code messy is that I havent been able to successfully get my Async Http Request Responses out of onSuccess() so that the data is available to the rest of the class freely. Up till this point I have been parsing all my request responses inside the curlys of my responsehandlers onSuccess(){}

I came across this post on Stack: How to get the result of OnPostExecute() to main activity because AsyncTask is a separate class?

but have yet to get it to work with this lib.

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;
  }
}




import org.json.*;
import com.loopj.android.http.*;

class TwitterRestClientUsage {
    public void getPublicTimeline() throws JSONException {
        TwitterRestClient.get("statuses/public_timeline.json", null, new JsonHttpResponseHandler() {
            @Override
            public void onSuccess(JSONArray timeline) {
                // Pull out the first event on the public timeline
                JSONObject firstEvent = timeline.get(0);
                String tweetText = firstEvent.getString("text");

                // Do something with the response
                System.out.println(tweetText);
            }
        });
    }
}

I do not know if this helps, but I have had to face the same problem (I am quite the novice at java and android). Used an interface. http://www.gdgankara.org/2013/03/25/android-asynchronous-http-client-a-callback-based-http-client-library-for-android-and-android-smart-image-view/

Try this:

public static void get(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
                client.get(getAbsoluteUrl(url), params, responseHandler);
                String response = new String(responseHandler);
                Log.i("RESPONSE", response);
            }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM