我正在尝试从 github api 获得用户 json 列表的响应。
谁能告诉我代码执行路径没有达到覆盖方法onFailure()和onSuccess的原因?
public String getResponse()
{
AsyncHttpClient client=new AsyncHttpClient();
RequestParams params=new RequestParams();
params.put("since","0");
client.get("https://api.github.com/users", params, new AsyncHttpResponseHandler() {
@Override
public void onFailure(int arg0, Header[] arg1, byte[] arg2,
Throwable arg3) {
userList.clear();
userList.addFirst("Items didn't load properly");
}
@Override
public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
try {
content = new String(arg2, "UTF-8");
//content is json response that can be parsed.
} catch (UnsupportedEncodingException e1) {
userList.clear();
userList.add("Some encoding problems occured");
e1.printStackTrace();
}
}
});
return content;
}
由于某种原因,这些方法只是被忽略了。在client.get(...)之后,它会向右跳转以返回 content。
关于它的原因有什么想法吗?我究竟做错了什么?
将不胜感激任何建议。
编辑:所以正确的方法是在onSuccess(...)方法 中使用响应进行操作?
@Override
public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
try {
content = new String(arg2, "UTF-8");
//content is json response that can be parsed.
parseResponseAmount(content, 10); //operate with response
} catch (UnsupportedEncodingException e1) {
userList.clear();
userList.add("Some encoding problems occured");
e1.printStackTrace();
}
}
我尝试从响应中解析信息,例如:
private void parseResponseAmount (String response, int amount)
{
try {
JSONArray readerArray = new JSONArray(response);
for (int i = 0; i < amount; i++)
{
JSONObject userObject = (JSONObject) readerArray.get(i);
String login = userObject.getString("login");
getUserList().add(login);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
getUserList().clear();
getUserList().add("Failed to parse response");
e.printStackTrace();
}
}
但该代码仍然不起作用。在事件驱动开发中,它由鼠标移动、按键等引起。是什么导致这些onSuccess()和onFailure()发生?前提是什么?