标签:
public class MyAsy extends AsyncTask<String, Integer, String> {
private String json;
@Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
// 实例化HttpClient
HttpClient client = new DefaultHttpClient();
// 设置请求方式
HttpGet httpGet = new HttpGet(params[0]);
try {
// 请求数据
HttpResponse execute = client.execute(httpGet);
// 通过状态行得到状态码
int statusCode = execute.getStatusLine().getStatusCode();
// 判断状态码是否是200 是 请求成功
if (statusCode == 200) {
HttpEntity entity = execute.getEntity();
// 拿到请求的数据
json = EntityUtils.toString(entity);
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return json;
}
}
// 实例化AsyncTask
MyAsy myAsy = new MyAsy();
try {
// 异步交互拿到数据
String string = myAsy.execute(" ").get();
} catch (InterruptedException | ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Handler handler = new Handler() {
public void handleMessage(android.os.Message msg) {
if (msg.what == 1) {
String str = (String) msg.obj;
}
};
};
new Thread() {
@Override
public void run() {
// TODO Auto-generated method stub
super.run();
HttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet("添加网址");
try {
HttpResponse execute = client.execute(httpGet);
int statusCode = execute.getStatusLine().getStatusCode();
if (statusCode == 200) {
HttpEntity entity = execute.getEntity();
String json = EntityUtils.toString(entity);
Message msg = Message.obtain();
msg.what = 1;
msg.obj = json;
handler.sendMessage(msg);
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}.start();
httpclient + AsyncTask 请求数据 || httpclient + handler 请求数据
标签:
原文地址:http://www.cnblogs.com/cuizhe/p/5405615.html