我需要向包含json数据的url发出get请求,并尝试使用Loopj库,但它没有返回任何内容。我试着在网上找一些例子,但结果发现它们可能已经过时了(onSuccess方法有不同的参数)。我试着让我的代码适应这个例子,我得到的是:
String AllData=""; AsyncHttpClient client = new AsyncHttpClient();
client.get("wantedUrl", new AsyncHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
for (byte aResponseBody : responseBody) {
AllData += aResponseBody;
}
}
@Override
public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
Toast.makeText(getApplicationContext(),"We got an error",Toast.LENGTH_SHORT).show();
}
});
"wantedUrl"是json格式的url,但"AllData"仍然为空。如何解决这个问题?
你在需要JsonHttpResponseHandler
的地方得到了AsyncHttpResponseHandler
回调。使用下面的代码让事情走上正轨。
String AllData=""; AsyncHttpClient client = new AsyncHttpClient();
client.get("wantedUrl", new JsonHttpResponseHandler(){
@Override
public void onSuccess(int statusCode, Header[] headers, JSONArray response) {
super.onSuccess(statusCode, headers, response);
//Here response will be received in form of JSONArray
}
@Override
public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
super.onSuccess(statusCode, headers, response);
//Here response will be received in form of JSONObject
}
@Override
public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
super.onFailure(statusCode, headers, responseString, throwable);
Toast.makeText(getApplicationContext(), "We got an error", Toast.LENGTH_SHORT).show();
}
});