标签:
Handler handler = new Handler(new android.os.Handler.Callback() {
@Override
public boolean handleMessage(Message msg) {
switch (msg.arg1) {
case 1:
// 对获取的数据进行操作
break;
case 2:
// 对获取到数据进行操作
break;
default:
break;
}
return false;
}
});
//联网前,检查网络的操作在此省略不写。
public void sendWebRequest() {
new Thread(new Runnable() {
@Override
public void run() {
HttpURLConnection conn = null;
try {
URL url = new URL("www.baidu.com");
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");// get请求方式:从服务端读取数据
/*
* post:将数据提交到服务端。 注意点: 每条数据以键值对形式存在 数据间用 & 分隔
* conn.setRequestMethod("POST"); //post:将数据提交到服务端
* DataOutputStream dataoutputstream=new DataOutputStream( conn.getOutputStream() );
* dataoutputstream.writeBytes("username=haha&password=123456" ); //每条数据以键值对形式存在,数据间用 & 分隔
*/
conn.setConnectTimeout(8 * 1000);
conn.setReadTimeout(1000 * 8);
conn.connect();
BufferedReader reader = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
StringBuffer buffer = new StringBuffer(); // 用于存储获取到的数据
String line;
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
// 注意点: 子线程不能对UI控件操作,需要到主线程(即UI线程)才能操作ui控件
Looper.prepare();
Message message = handler.obtainMessage();
message.obj = buffer;
message.arg1 = 1;
handler.sendMessage(message);
Looper.loop();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (conn != null) {
conn.disconnect();
}
}
}
}).start();
}
public void sendhttpconnet() {
new Thread(new Runnable() {
public void run() {
try {
// HttpClient是一个接口,不能new 本身。 故new 一个默认的httpclient
HttpClient httpclient = (HttpClient) new DefaultHttpClient();
HttpGet get = new HttpGet("http://www.baidu.com"); // get请求
/*
* post 请求:提交数据到服务端,或者上传文件到服务端 HttpPost post=new
* HttpPost("http://www.baidu.com"); List<NameValuePair>
* parameters=new ArrayList<NameValuePair>(); //用来存放数据
* parameters.add(new BasicNameValuePair("name", "admin"));
* parameters.add(new BasicNameValuePair("pwd", "123456"));
* UrlEncodedFormEntity entity1=new UrlEncodedFormEntity(parameters, "utf-8");
* post.setEntity(entity1);
*/
HttpResponse respone = httpclient.execute(get);
// 判断是否请求成功
if (respone.getStatusLine().getStatusCode() == 200) {
HttpEntity entity = respone.getEntity();
String s = EntityUtils.toString(entity, "utf-8"); // 转换成 String 类型
Looper.prepare();
Message message = handler.obtainMessage();
message.obj = s;
message.arg1 = 2;
handler.sendMessage(message);
Looper.loop();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}
标签:
原文地址:http://my.oschina.net/u/2406195/blog/482787