使用HTTP协议访问网路
一、使用HttpURLConnection
//new一个URL对象
URL url = new URL("http://www.qq.com");//千万不要用www.baidu.com,坑爹东西
//调用openConnection()方法,得到HttpURLConnection对象
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
//对HttpURLConnection对象设置模式,GET 表示希望从服务器那里获取数据,而 POST 则表示希望提交数据给服务器。
connection.setRequestMethod("GET");
//设置连接超时、读取超时的毫秒数
connection.setConnectTimeout(8000);
connection.setReadTimeout(8000);
//调用 getInputStream()方法获取到服务器返回的输入流
InputStream in = connection.getInputStream();
//对输入流进行读取操作
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder response = new StringBuilder();
String line;
//当该行不为空,返回一行
while ((line = reader.readLine()) != null) {
Log.d(TAG, "line != null" + line);
response.append(line);
}
//通过handler把message发送出去
Message message = new Message();
message.what = SHOW_RESPONSE;
if (response.toString() == null) {
message.obj = response.toString() + "啥也没有";
} else {
message.obj = response.toString();
}
mHandler.sendMessage(message);
主线程中创建handler,并重写handlerMessage()方法,等待来自sendMessage的信息
private Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case SHOW_RESPONSE:
//判断信息并更新UI操作
String response = (String) msg.obj;
NetworkTextView.setText(response);
break;
}
}
};
向服务器推送数据
connection.setRequestMethod("POST");
DataOutputStream out = new DataOutputStream(connection.getOutputStream());
out.writeBytes("username=admin&password=123456");//数据与数据之间用"&"隔开