Android使用HTTP协议访问网络

来源:互联网 发布:网络准入控制 界面 编辑:程序博客网 时间:2024/06/05 11:07

        在 Android 上发送 HTTP 请求的方式一般有两种,HttpURLConnection 和 HttpClient,我们先来学习一下 HttpURLConnection 的用法。


HttpURLConnection用法

        首先需要获取到 HttpURLConnection 的实例,一般只需 new 出一个 URL 对象,并传入目标的网络地址,然后调用一下 openConnection()方法即可,如下所示:

URL url = new URL("http://www.baidu.com");HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        得到了 HttpURLConnection 的实例之后,我们可以设置一下 HTTP 请求所使用的方法。常用的方法主要有两个,GET 和 POST。GET 表示希望从服务器那里获取数据,而 POST 则表示希望提交数据给服务器。写法如下:

connection.setRequestMethod("GET");
        接下来就可以进行一些自由的定制了,比如设置连接超时、读取超时的毫秒数,以及服务器希望得到的一些消息头等。这部分内容根据自己的实际情况进行编写,示例写法如下:

connection.setConnectTimeout(8000);connection.setReadTimeout(8000);
        之后再调用 getInputStream()方法就可以获取到服务器返回的输入流了, 剩下的任务就是对输入流进行读取,如下所示:

InputStream in = connection.getInputStream();
        最后可以调用 disconnect()方法将这个 HTTP 连接关闭掉,如下所示:

connection.disconnect();

HttpClient用法

        HttpClient是 Apache 提供的 HTTP 网络访问接口, 从一开始的时候就被引入到了 AndroidAPI 中。它可以完成和 HttpURLConnection 几乎一模一样的效果,但两者之间的用法却有较大的差别,那么我们自然要看一下 HttpClient 是如何使用的了。
        首先你需要知道,HttpClient 是一个接口,因此无法创建它的实例,通常情况下都会创建一个 DefaultHttpClient 的实例,如下所示:

HttpClient httpClient = new DefaultHttpClient();
        接下来如果想要发起一条 GET 请求,就可以创建一个 HttpGet 对象,并传入目标的网络地址,然后调用 HttpClient 的 execute()方法即可:

HttpGet httpGet = new HttpGet("http://www.baidu.com");httpClient.execute(httpGet);

使用示例

activity_main.xml布局文件源码

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:orientation="vertical" >    <Button        android:id="@+id/send_request"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:text="Send Request - HttpURLConnection" />    <Button        android:id="@+id/send_request2"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:text="Send Request - HttpClient" />    <ScrollView        android:layout_width="match_parent"        android:layout_height="match_parent">        <TextView            android:id="@+id/response_text"            android:layout_width="match_parent"            android:layout_height="wrap_content" />    </ScrollView></LinearLayout>

MainActivity.java源码

package com.example.luoxn28.activity;import android.app.Activity;import android.os.Bundle;import android.os.Message;import android.view.View;import android.widget.Button;import android.widget.TextView;import android.os.Handler;import org.apache.http.HttpEntity;import org.apache.http.HttpResponse;import org.apache.http.client.HttpClient;import org.apache.http.client.methods.HttpGet;import org.apache.http.impl.client.DefaultHttpClient;import org.apache.http.util.EntityUtils;import java.io.BufferedReader;import java.io.InputStream;import java.io.InputStreamReader;import java.net.HttpURLConnection;import java.net.URL;public class MainActivity extends Activity implements View.OnClickListener {    private static final String TAG = "hdu";    public static final int SHOW_RESPONSE = 0;    private Button sendRequest;    private Button sendRequest2;    private TextView responseText;    private Handler handler = new Handler() {        public void handleMessage(Message msg) {            switch (msg.what) {                case SHOW_RESPONSE:                    String response = (String) msg.obj;                    // 更新UI界面                    responseText.setText(response);                    break;                default:                    break;            }        }    };    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        //requestWindowFeature(Window.FEATURE_NO_TITLE);        setContentView(R.layout.activity_main);        sendRequest = (Button) findViewById(R.id.send_request);        sendRequest2 = (Button) findViewById(R.id.send_request2);        responseText = (TextView) findViewById(R.id.response_text);        sendRequest.setOnClickListener(this);        sendRequest2.setOnClickListener(this);    }    @Override    public void onClick(View v) {        switch (v.getId()) {            case R.id.send_request:                sendRequestWithHttpURLConnection();                break;            case R.id.send_request2:                sendRequestWithHttpClient();                break;            default:                break;        }    }    private void sendRequestWithHttpClient() {        new Thread(new Runnable() {            @Override            public void run() {                try {                    HttpClient httpClient = new DefaultHttpClient();                    HttpGet httpGet = new HttpGet("http://www.baidu.com");                    HttpResponse httpResponse = httpClient.execute(httpGet);                    if (httpResponse.getStatusLine().getStatusCode() == 200) {                        // 请求和响应成功                        HttpEntity entity = httpResponse.getEntity();                        String response = EntityUtils.toString(entity, "utf-8");                        Message message = new Message();                        message.what = SHOW_RESPONSE;                        message.obj = response.toString();                        handler.sendMessage(message);                    }                }                catch (Exception ex) {                    ex.printStackTrace();                }            }        }).start();    }    private void sendRequestWithHttpURLConnection() {        // 开启线程进行发起网络连接        new Thread(new Runnable() {            @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);                }                catch (Exception ex) {                    ex.printStackTrace();                }                finally {                    if (connection != null) {                        connection.disconnect();                    }                }            }        }).start();    }}

AndroidMaintest.xml文件声明权限

        在AndroidManifest.xml中声明网络权限

<uses-permission android:name="android.permission.INTERNET" />

参考资料

        1、《第一行代码 Android》使用网络技术章节


0 0