我的应用程序从服务器获取多个Json信息
目标寻找任何方式在没有Http
的情况下执行AsyncTask
请求,有没有办法做到这一点,或者我必须继续使用AsyncTask
从服务器获取Json信息?< / p>
答案 0 :(得分:2)
我建议看看Android Asynchronous Http Client (Loopj) library。这是“典型”http请求的示例。
AsyncHttpClient client = new AsyncHttpClient();
client.get("http://www.google.com", new AsyncHttpResponseHandler() {
@Override
public void onSuccess(String response) {
System.out.println(response);
}
});
答案 1 :(得分:0)
这就是你如何做到这一点
public class RequestClient extends AsyncTask<String, Void, String>{
Context context;
public RequestClient(Context c) {
context = c;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected String doInBackground(String... aurl){
String responseString="";
HttpClient client = null;
try {
client = new DefaultHttpClient();
HttpGet get = new HttpGet(LoginActivity.url);
HttpResponse responseGet = client.execute(get);
HttpEntity resEntityGet = responseGet.getEntity();
if (resEntityGet != null) {
responseString = EntityUtils.toString(resEntityGet);
Log.i("GET RESPONSE", responseString.trim());
}
} catch (Exception e) {
Log.d("ANDRO_ASYNC_ERROR", "Error is "+e.toString());
}
Log.d("ANDRO_ASYNC_RESPONSE", responseString.trim());
client.getConnectionManager().shutdown();
return responseString.trim();
}
@Override
protected void onPostExecute(String response) {
super.onPostExecute(response);
}
}
你必须从主类中将其称为
RequestClient reqClient = new RequestClient(this);
reqClient.execute().get();