从AsyncHttpClient获取响应

时间:2013-08-11 08:22:52

标签: java android asynchronous android-asynctask httpresponse

我正在使用此lib:http://loopj.com/android-async-http/来完成我的所有请求&&目前使代码混乱的最大问题是我无法成功地从onSuccess()中获取异步Http请求响应,以便数据可以自由地用于其余类。到目前为止,我一直在解析我的响应处理程序中的所有请求响应onSuccess(){}

我在Stack上发现了这篇文章:How to get the result of OnPostExecute() to main activity because AsyncTask is a separate class?

但尚未使用此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);
            }
        });
    }
}

2 个答案:

答案 0 :(得分:0)

我不知道这是否有帮助,但我不得不面对同样的问题(我是java和android的新手)。使用了一个界面。 http://www.gdgankara.org/2013/03/25/android-asynchronous-http-client-a-callback-based-http-client-library-for-android-and-android-smart-image-view/

答案 1 :(得分:0)

尝试一下:

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