Android开发----AsyncTask请求数据
自建AsyncTask类
public class MAsyncTask extends AsyncTask<String, Integer, String>{
@Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(params[0]);
//请求网络数据
String string = null;
try {
HttpResponse response = httpClient.execute(httpPost);
if(response.getStatusLine().getStatusCode() == 200){
HttpEntity entity = response.getEntity();
string = EntityUtils.toString(entity,"GBK");
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return string;
}
}
mainactivity使用asynctask
MAsyncTask asyncTask = new MAsyncTask();
// 得到AsyncTask联网请求到的数据
try {
String string = asyncTask.execute(uil).get();
bejson(string);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}