使用HTTP协议访问网络

来源:互联网 发布:js 运行时未定义变量 编辑:程序博客网 时间:2024/05/24 05:08

1.使用HttpURLConnection

      在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则表示希望提交数据给服务器。写法如下:

      connection.setRequestMethod("GET");

      此外就是设置连接超时,读取超时的毫秒数,以及服务器希望得到的一些消息头等。

      connection.setConnectTimeout(8000);

      connection.setReadTimeout(8000);

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

      InputStream in = connection.getInputStream();

      最后调用disconnect()方法将这个HTTP连接关闭掉,如下所示:

      connection.disconnect();

      新建一个Network项目,首先修改activity_main.xml中的代码,如下所示:

<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:orientation="vertical"    tools:context=".MainActivity" >    <Button        android:id="@+id/btnSendRequest"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:onClick="sendRequest"        android:text="Send Request" />    <ScrollView        android:layout_width="match_parent"        android:layout_height="match_parent" >        <TextView            android:id="@+id/tvRespones"            android:layout_width="match_parent"            android:layout_height="wrap_content"                       android:text="TextView" />    </ScrollView></LinearLayout>
      这里我们用了一个新的控件ScrollView,借用ScrollView控件的话就可以允许我们以滚动的形式查看屏幕外的那部分内容。另外,布局中还放置了一个Button和一个TextView

Button用于发送HTTP请求,TextView用于将服务器返回的数据显示出来。

      接着修改MainActivity中的代码,如下所示:

package com.example.nettest;import java.io.BufferedReader;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import java.net.HttpURLConnection;import java.net.MalformedURLException;import java.net.URL;import android.app.Activity;import android.os.Bundle;import android.os.Handler;import android.os.Message;import android.view.View;import android.widget.TextView;public class MainActivity extends Activity {    private TextView tvResponse;    public static final int SHOW_RESPONSE=1;    private Handler handler=new Handler(){    public void handleMessage(android.os.Message msg) {    switch (msg.what) {case  SHOW_RESPONSE:String content=(String) msg.obj;tvResponse.setText(content);break;default:break;}    };    };@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);tvResponse=(TextView) findViewById(R.id.tvRespones);}public void sendRequest(View view){sendRequestWithHttpUrlConnection();}private void sendRequestWithHttpUrlConnection() {new Thread(){public void run() {HttpURLConnection httpURLConnection=null;        try {//获取HttpURLConnection的实例,new出对象,传入目标的网络地址,调用OpenConnection方法URL url=new URL("http://www.baidu.com");httpURLConnection=(HttpURLConnection) url.openConnection();httpURLConnection.setRequestMethod("GET");//get请求,从服务器那里获取数据httpURLConnection.setConnectTimeout(6000);//设置连接超时InputStream is=httpURLConnection.getInputStream();//获取服务器返回的输入流//下面是对获取到的输入流进行读取BufferedReader br=new BufferedReader(new InputStreamReader(is));String s;StringBuilder sb=new StringBuilder();while((s=br.readLine())!=null){sb.append(s);}Message message=new Message();message.what=SHOW_RESPONSE;//将服务器返回的结果存放到Message中message.obj=sb.toString();handler.sendMessage(message);System.out.println("getContent="+sb.toString());} catch (MalformedURLException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}finally{httpURLConnection.disconnect();//关闭Http连接}};}.start();}}
       可以看到,我们在Send  Requset按钮的点击事件中调用了sendRequestWithHttpURLConnection()方法,在这个方法中先是开启了子线程,然后在子线程中使用HttpURL-

Connection发出一条HTTP请求,请求的目标地址就是百度的首页;接着利用BufferedReader对服务器返回的流进行读取,并将结果存放到Message对象中。

       完整的一套流程就是这样,在运行程序之前,不要忘了声明一下网络权限,修改AndroidMainifest.xml中的代码,如下所示:

 <uses-permission android:name="android.permission.INTERNET"/>
程序运行结果如下所示:

2.使用HttpClient

       HttpClient是Apache提供的HTTP网络访问接口,从一开始的时候就被引用到了Android API中。它可以完成和HttpURLConnection几乎一模一样的效果,但两者之间的用法却

有很大的差别。

       首先我们要知道,HttpClient是一个接口,因此无法创建它的实例,这里我们创建一个DefaultHttpClient的实例,如下所示:

       HttpClient  httpClient = new DefaultHttpClient();

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

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

       httpClient.execute(httpGet);

       如果是发起一条POST请求会比get稍微复杂一些,我们要创建一个HttpPost对象,并传入目标的网络地址,如下所示:

       HttpPost  httpPost = new HttpPost("http://www.baidu.com");

       然后通过一个NameValuePair集合来存放待提交的参数,并将这个参数集合传入到一个UrlEncodedEntity中,然后调用HttpPost的setEntity()方法将构建好的UrlEncodedEntity传入,如下所示:

       List<NameValuePair> params =new ArrayList<NameValuePair>();

       params.add(newBasicNameValuePair("username", "admin"));

       params.add(newBasicNameValuePair("password", "123456"));

       UrlEncodedFormEntity entity = newUrlEncodedFormEntity(params, "utf-8");

       httpPost.setEntity(entity);

       然后调用HttpClient的execute()方法,并将HttpPost对象传入:

       httpClient.execute(httpPost);

       执行execute()方法之后会返回一个HttpResponse对象,服务器所返回的所有信息就会包含在这里面。通常情况下我们都会先取出服务器返回的状态码,如果等于200就说明请求和响应都成功了,如下所示:

       if (httpResponse.getStatusLine().getStatusCode()== 200) {

    //请求和响应都成功了

}

      接下来在这个if判断的内部取出服务返回的具体内容,可以调用getEntity()方法获取到一个HttpEntity实例,然后再用EntityUtils.toString()这个静态方法将HttpEntity转换成字符串即可,如下所示:

       HttpEntity entity =httpResponse.getEntity();

       String response = EntityUtils.toString(entity);

       如果服务器返回的数据是带有中文的,直接调用EntityUtils.toString()方法进行转换会有乱码的情况出现,这个时候只需要在转换的时候将字符集指定成utf-8就可以了,如下所示:

       String response =EntityUtils.toString(entity, "utf-8");

       由于布局不用改动,直接修改MainActivity中的代码,如下所示:

public class MainActivity extends Activity implements OnClickListener {……@Overridepublic void onClick(View v) {if (v.getId() == R.id.send_request) {sendRequestWithHttpClient();}}private void sendRequestWithHttpClient() {new Thread(new Runnable() {@Overridepublic 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中message.obj = response.toString();handler.sendMessage(message);}} catch (Exception e) {e.printStackTrace();}}}).start();}……}

      这里我们只是添加了一个sendRequestWithHttpClient()方法,并在Send Request按钮的点击事件里去调用这个方法。在这个方法中同样还是先开启了一个子线程,然后在子线程里使用HttpClient发出一条HTTP请求,请求的目标地址还是百度的首页,HttpClient的用法也正如前面所介绍的一样。然后为了能让结果在界面上显示出来,这里仍然是将服务器返回的数据存放到了Message对象中,并用Handler将Message发送出去。

仅仅只是改了这么多代码,现在我们可以重新运行一下程序了。点击Send Request按钮后,你会看到和上一小节中同样的运行结果,由此证明,使用HttpClient来发送HTTP请求的功能也已经成功实现了。

0 0