Android使用Http协议访问网络

来源:互联网 发布:猫池软件 编辑:程序博客网 时间:2024/06/05 08:05

两种访问方法1、使用HttpURLConnection 2、HttpClient

一、使用HttpURLConnection访问网络
布局代码

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"    android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"    android:paddingRight="@dimen/activity_horizontal_margin"    android:paddingTop="@dimen/activity_vertical_margin"    android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity"    android:orientation="vertical">    <Button        android:id="@+id/send_request"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:text="发送请求"/>    <ScrollView        android:layout_width="match_parent"        android:layout_height="match_parent">        <TextView            android:id="@+id/request_text"            android:layout_width="match_parent"            android:layout_height="match_parent" />    </ScrollView></LinearLayout>

通过点击一个按钮发送http请求,将返回的信息显示在TextView中

public class MainActivity extends ActionBarActivity implements View.OnClickListener {    private static final int SHOWRESPONSE = 0;    private Button send_request;    private TextView request_text;    private Handler handler = new Handler() {        @Override        public void handleMessage(Message msg) {            switch (msg.what){                case SHOWRESPONSE:                    request_text.setText(msg.obj.toString());                    break;                default:                    break;            }        }    };    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        send_request = (Button)findViewById(R.id.send_request);        request_text = (TextView)findViewById(R.id.request_text);        send_request.setOnClickListener(this);    }    @Override    public void onClick(View v) {        switch (v.getId()){            case R.id.send_request:                SendHttpConnection();                break;            default:                break;        }    }    private void SendHttpConnection() {        new Thread(new Runnable() {            @Override            public void run() {                //创建实例                HttpURLConnection connection = null;                try {                    URL url = new URL("http://www.baidu.com");                    //建立连接                    connection = (HttpURLConnection) url.openConnection();                    //设置get方法                    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 message = new Message();                    message.what = SHOWRESPONSE;                    message.obj = response.toString();                    handler.sendMessage(message);                } catch (MalformedURLException e) {                    e.printStackTrace();                } catch (IOException e) {                    e.printStackTrace();                }            }        }).start();    }}

创建HttpURLConnection实例之后,我们可以设置请求方法,一个是get方法一个是post方法,get方法是从服务器端获取数据,post方法是向服务器端发送数据。

如果用post方法的话需要先将HTTP请求的方法换为post,并在获取输入流之前将需要post的数据写出即可,注意每条数据是以键值对形式存在的,数据之间用&间隔。

connection.setRequestMethod("post");DataOutputStream out = new DataOutputStream(connection.getOutpitStream());out.writeBytes("username=admin&password=123");

二、HttpClient方法
HttpClient是一个接口,所以我们没法实例化,通常情况会创建一个DefaultHttpClient的实例。
什么是接口

public class MainActivity extends ActionBarActivity implements View.OnClickListener {    private static final int SHOWRESPONSE = 0;    private Button send_request;    private TextView request_text;    private Handler handler = new Handler() {        @Override        public void handleMessage(Message msg) {            switch (msg.what){                case SHOWRESPONSE:                    request_text.setText(msg.obj.toString());                    break;                default:                    break;            }        }    };    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        send_request = (Button)findViewById(R.id.send_request);        request_text = (TextView)findViewById(R.id.request_text);        send_request.setOnClickListener(this);    }    @Override    public void onClick(View v) {        switch (v.getId()){            case R.id.send_request:                SendHttpClient();                break;            default:                break;        }    }    private void SendHttpClient() {        new Thread(new Runnable() {            @Override            public void run() {                HttpClient httpClient = new DefaultHttpClient();                HttpGet httpGet = new HttpGet("http://www.baidu.com");                try {                    //调用execute方法执行请求                    HttpResponse httpResponse = httpClient.execute(httpGet);                    //执行execute方法之后会返回一个HttpResponse对象,返回的所有信息都在里面,如果其中的状态码                    //为200的话就说明请求和响应成功了。                    if(httpResponse.getStatusLine().getStatusCode() == 200){                        //请求响应成功                        HttpEntity entity = httpResponse.getEntity();                        //如果服务器传回的数据含有中文,需要改成utf8编码。                        String response = EntityUtils.toString(entity, "utf-8");                        Message message = new Message();                        message.what = SHOWRESPONSE;                        message.obj = response.toString();                        handler.sendMessage(message);                    }                } catch (IOException e) {                    e.printStackTrace();                }            }        }).start();    }}

记得声明联网权限

<uses-permission android:name="android.permission.INTERNET"></uses-permission>
0 0
原创粉丝点击