1 Http协议:它的工作原理特别的简单,就是客户端向服务器发出一条HTTP 请求,服务器收到请求之后会返回一些数据给客户端,然后客户端再对这些数据进行解析和处理就可以了。
2 在Android 上发送HTTP 请求的方式一般有两种,HttpURLConnection 和HttpClient。
HttpURLConnection:
首先需要获取到HttpURLConnection 的实例,一般只需new 出一个URL 对象,并传入
目标的网络地址,然后调用一下openConnection()方法即可,如下所示:“`
URL url = new URL("http://www.baidu.com");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
得到了HttpURLConnection 的实例之后,我们可以设置一下HTTP 请求所使用的方法。
常用的方法主要有两个,GET 和POST。GET 表示希望从服务器那里获取数据,而POST 则
表示希望提交数据给服务器。
之后再调用getInputStream()方法就可以获取到服务器返回的输入流了,剩下的任务就是
对输入流进行读取,如下所示:
InputStream in = connection.getInputStream();
最后可以调用disconnect()方法将这个HTTP 连接关闭掉,如下所示:
connection.disconnect();
3 实际使用
public class MainActivity extends Activity implements OnClickListener {
public static final int SHOW_RESPONSE = 0;
private Button sendRequest;
private TextView responseText;
private Handler handler = new Handler() {
//Handler是用来处理接收子进程传来的数据,将其更新在UI上
public void handleMessage(Message msg) {//子类必须重写此方法,接受数据
switch (msg.what) {
case SHOW_RESPONSE:
String response = (String) msg.obj;
// 在这里进行UI操作,将结果显示到界面上
responseText.setText(response);
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sendRequest = (Button) findViewById(R.id.send_request);
responseText = (TextView) findViewById(R.id.response_text);
sendRequest.setOnClickListener(this);
}
@Override
public void onClick(View v) {
if (v.getId() == R.id.send_request) {
sendRequestWithHttpURLConnection();//创建新的线程
}
}
private void sendRequestWithHttpURLConnection() {
// 开启线程来发起网络请求
new Thread(new Runnable() {//匿名类,并重写run这个方法。此为开启新的进程的方法。
@Override
public void run() {
HttpURLConnection connection = null;
try {
URL url = new URL("http://www.baidu.com");
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setConnectTimeout(8000);
connection.setReadTimeout(8000);
InputStream in = connection.getInputStream();
// 下面对获取到的输入流进行读取
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder response = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
response.append(line);
}
Message message = new Message();
message.what = SHOW_RESPONSE;
// 将服务器返回的结果存放到Message中
message.obj = response.toString();
handler.sendMessage(message);//发送数据,与handleMessage(Message msg) 对应
} catch (Exception e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
}
}
}).start();
}
}