【发布时间】:2014-11-14 20:22:14
【问题描述】:
我正在寻找一种方法来返回我在 loopJ AsyncHttpClient onFinish 或 onSuccess 或 onFailure 中得到的响应。截至目前,我有这段代码:
**jsonParse.java file**
public class jsonParse {
static JSONObject jObj = null;
static String jsonString = "";
AsyncHttpClient client;
public JSONObject getJSONObj() {
RequestParams params;
params = new RequestParams();
params.add("username", "user");
params.add("password", "password");
client = new AsyncHttpClient();
client.post("http://example.com", params, new TextHttpResponseHandler() {
@Override
public void onSuccess(int i, Header[] headers, String response) {
jsonString = response;
Log.d("onSuccess: ", jsonString);
}
@Override
public void onFailure(int statusCode, Header[] headers, String response, Throwable e) {
if (statusCode == 401) {
jsonString = response;
Log.d("onFailure: ", jsonString);
}
}
});
try {
jObj = new JSONObject(jsonString);
} catch (JSONException e) {
Log.e("Exception", "JSONException " + e.toString());
}
return jObj;
}
}
当我调用代码时:
JSONParser jsonParser = new JSONParser();
jsonParser.getJSONFromUrl();
我在 onSuccess 或 onFailure 方法完成 http post 之前得到 JSONException。
我注意到,在第一次调用时: Log.e("异常", "JSONException" + e.toString());正在记录,然后 Log.d("onSuccess: ", jsonString);记录处于同步状态的值。
在第二次调用时: jObj = new JSONObject(jsonString);成功执行,我得到了该方法所需的返回值,因为到那时 onSuccess 方法已经将值分配给变量 jsonString。
现在我正在寻找的是一种防止 过早 从方法中返回 jObj 的方法。
有没有办法制作getJSONObj方法,等待AsyncHttpClient任务完成,将变量赋值给jsonString,创建JSONObject并返回?
提前致谢! 干杯!
【问题讨论】:
-
@mapo87 感谢您的早日回复。我有一个关于改造的问题,它是否支持 https post 和持久性 Cookie 存储?
-
https:是的,cookies:你需要设置,但是是的
-
@mapo87 感谢您的回复。我会注意的:)
标签: java android android-asynctask loopj asynchttpclient