我使用LoopJ AndroidAsyncHttp从url获取响应,但代码没有进入onSuccess()或onFailure()。代码如下:
public void queryTopic(RequestParams params) {
AsyncHttpClient client = new AsyncHttpClient();
client.get("http://192.168.0.109:8080/PhoneServer/topic/query", params, new AsyncHttpResponseHandler() {
@Override
public void onSuccess(String response) {
System.out.println("It's in onSuccess");
}
// When the response returned by REST has Http response code
// other than '200'
@Override
public void onFailure(int statusCode, Throwable error,
String content) {
System.out.println("It's in onFailure");
}
});
System.out.println("It's over");
}
它刚打印出“它结束了”。 AsyncHttpClient有什么问题?
答案 0 :(得分:0)
你怎么称呼这个?背景是否存在?如果你从一个上下文不再可用的地方调用它,那么你永远不会得到这个回调。
我认为您应该尝试在点击某个按钮时调用此queryTopic()方法然后等待一段时间,您应该得到响应。
答案 1 :(得分:0)
可能问题是你向服务器询问了一个字符串
public void onSuccess(String response){...}
但服务器使用JSONObject回答
您可以尝试以下代码:
AsyncHttpClient client = new AsyncHttpClient();
client.setTimeout(5000);
client.get(yourActivity.class, yourLink, new JsonHttpResponseHandler(){
@Override
public void onStart() {
Log.e(TAG, "start");
}
@Override
public void onSuccess(int status, Header[] headers, JSONObject answer) {
Log.e(TAG, "SUCCESS");
Log.e(TAG, "print => "+answer.getString("answer_id")); //"answer_id" is a random example
}
@Override
public void onFailure(int status, Header[] headers, String answer, Throwable throwable) {
Log.e(TAG, "FAILURE");
}
});
答案 2 :(得分:0)
onSuccess()
是一种重载方法,请注意从服务器发送的内容,
如果是jsonObject或jsonArray或简单字符串。使用onSuccess()的相应重载方法。我也将它用于jsonObject响应,并且在方法中没有遇到错误或异常。
我从服务器返回jsonObject,我的代码对其工作正常,如下所示:
RequestParams params = new RequestParams();
params.put("pet","Cat");
params.put("name","Maran");
RestClient.get("/savelocation", params, new JsonHttpResponseHandler(){
@Override
public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
Toast.makeText(context,response.toString(),Toast.LENGTH_SHORT).show();
Log.e("Error makerequest","request completed");
}
@Override
public void onFinish() {
//onLoginSuccess();
}
@Override
public void onFailure(int statusCode, Header[] headers, Throwable throwable,JSONObject errorResponse){
Toast.makeText(context,throwable.toString(),Toast.LENGTH_LONG).show();
}
});
注意:RestClient是AsyncHttpClient的静态实例