天天看点

Android http

浏览器与网站交互 首先建立连接,浏览器向网站发送请求,网站响应请求(并返回请求内容),浏览器关闭连接。

请求可以不带参数也可以带参数。如 ​​http://www.baidu.com​​​ 没有带参数。​​http://www.baidu.com/s?word=java&tn=site888_pg&lm=-1​​ 则是带参数

带参数的可以用 get方法发送,也可以用post 方式发送。

GET请求的数据会附在URL之后(就是把数据放置在HTTP协议头中),以?分割URL和传输数据,参数之间以&相连,如:login.action?name=hyddd&password=idontknow&verify=%E4%BD%A0%E5%A5%BD。如果数据是英文字母/数字,原样发送,如果是空格,转换为+,如果是中文/其他字符,则直接把字符串用BASE64加密,得出如:%E4%BD%A0%E5%A5%BD,其中%XX中的XX为该符号以16进制表示的ASCII。

POST把提交的数据则放置在是HTTP包的包体中。

代码示例:

package com.urlconnecttest;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends Activity {

  private TextView tv;
  private Button btn;
  private HttpResponse httpResponse = null;
  private HttpEntity httpEntity = null;

  private final String baseUrl = "http://www.baidu.com/";

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    setTitle("获取网站返回资源");
    init();
  }

  public void init() {

    tv = (TextView) findViewById(R.id.tv);
    btn = (Button) findViewById(R.id.btn);

    btn.setOnClickListener(new OnClickListener() {

      @Override
      public void onClick(View v) {
        // TODO Auto-generated method stub
        System.out.println("--- click! ---");

        new Thread(new Runnable() {

          @Override
          public void run() {
            // TODO Auto-generated method stub
            getRes();
          }
        }).start();
      }
    });
  }

  // get 方法测试
  public void getTest() {

    String url = baseUrl + "?" + "name=1&&age=20";
    HttpGet httpGet = new HttpGet(baseUrl);
    HttpClient httpClient = new DefaultHttpClient();
    InputStream is = null;
    try {
      httpResponse = httpClient.execute(httpGet);
      httpEntity = httpResponse.getEntity();

      BufferedReader br = new BufferedReader(new InputStreamReader(
          httpEntity.getContent()));
      String result = null;
      String line = null;
      while ((line = br.readLine()) != null) {
        result += line;
      }
      System.out.println("--- result: " + result + " ---");

    } catch (Exception e) {
      // TODO: handle exception
    }

    finally {
      try {
        is.close();
      } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
    }

  }

  public void postTest() {//Post 方法测试

    String name = "zhangsan";
    String age = "20";

    NameValuePair nameValuePair1 = new BasicNameValuePair("name", name);
    NameValuePair nameValuePair2 = new BasicNameValuePair("age", age);
    List<NameValuePair> list = new ArrayList<NameValuePair>();
    list.add(nameValuePair1);
    list.add(nameValuePair2);

    InputStream is = null;
    try {
      httpEntity = new UrlEncodedFormEntity(list);
      HttpPost httpPost = new HttpPost(baseUrl);
      HttpClient httpClient = new DefaultHttpClient();
      httpResponse = httpClient.execute(httpPost);
      httpEntity = httpResponse.getEntity();
      is = httpEntity.getContent();
      BufferedReader br = new BufferedReader(new InputStreamReader(is));
      String result = null, line = null;
      while ((line = br.readLine()) != null) {

        result += line;
      }
      System.out.println("--- result: " + result + " ---");

    } catch (UnsupportedEncodingException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (ClientProtocolException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }

    finally {
      try {
        is.close();
      } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
    }
  }

  public void getRes() {

    // 生成一个请求对象
    HttpGet httpGet = new HttpGet(baseUrl);
    // 生成一个http客户端对象
    HttpClient httpClient = new DefaultHttpClient();
    // 用http客户端发送请求对象
    InputStream is = null;
    try {
      httpResponse = httpClient.execute(httpGet);
      httpEntity = httpResponse.getEntity();
      is = httpEntity.getContent();
      BufferedReader br = new BufferedReader(new InputStreamReader(is));
      String result = null;
      String line = null;
      while ((line = br.readLine()) != null) {
        result += line;
      }

      System.out.println("--- result: " + result + " ---");
    } catch (ClientProtocolException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }

    finally {
      try {
        is.close();
      } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
    }
  }

}      

android 网络编程 HttpGet类和HttpPost类使用详解

内容来源于《人人都玩开心网》一书

        虽然在登录系统中使用了Web Service与服务端进行交互。但是在传递大量的数量时,Web Service显得有些笨拙。在本节将介绍移动电子相册中使用的另外一种与数据库交互的方法。直接发送HTTP GET或POST请求。这就要用到HttpGet、HttpPost以及HttpURLConnection这些类。

15.3.1  HttpGet类和HttpPost类

本节将介绍Android SDK集成的Apache HttpClient模块。要注意的是,这里的Apache HttpClient模块是HttpClient 4.0(org.apache.http.*),而不是Jakarta Commons HttpClient 3.x(org.apache.commons.httpclient.*)。

在HttpClient模块中用到了两个重要的类:HttpGet和HttpPost。这两个类分别用来提交HTTP GET和HTTP POST请求。为了测试本节的例子,需要先编写一个Servlet程序,用来接收HTTP GET和HTTP POST请求。读者也可以使用其他服务端的资源来测试本节的例子。

假设192.168.17.81是本机的IP,客户端可以通过如下的URL来访问服务端的资源:

​​http://192.168.17.81:8080/querybooks/QueryServlet?bookname=开发​​

在这里bookname是QueryServlet的请求参数,表示图书名,通过该参数来查询图书信息。

现在我们要通过HttpGet和HttpPost类向QueryServlet提交请求信息,并将返回结果显示在TextView组件中。

无论是使用HttpGet,还是使用HttpPost,都必须通过如下3步来访问HTTP资源。

1.创建HttpGet或HttpPost对象,将要请求的URL通过构造方法传入HttpGet或HttpPost对象。

2.使用DefaultHttpClient类的execute方法发送HTTP GET或HTTP POST请求,并返回HttpResponse对象。

public void onClick(View view)  
{  
    //  读者需要将本例中的IP换成自己机器的IP  
    String url = "http://192.168.17.81:8080/querybooks/QueryServlet";  
    TextView tvQueryResult = (TextView) findViewById(R.id.tvQueryResult);  
    EditText etBookName = (EditText) findViewById(R.id.etBookName);  
    HttpResponse httpResponse = null;  
    try  
    {  
        switch (view.getId())  
        {  
            //  提交HTTP GET请求  
            case R.id.btnGetQuery:  
                //  向url添加请求参数  
                url += "?bookname=" + etBookName.getText().toString();  
                //  第1步:创建HttpGet对象  
                HttpGet httpGet = new HttpGet(url);  
                //  第2步:使用execute方法发送HTTP 
 GET请求,并返回HttpResponse对象                  httpResponse = new DefaultHttpClient().execute(httpGet);  
                //  判断请求响应状态码,状态码为200表
 示服务端成功响应了客户端的请求                  if (httpResponse.getStatusLine().
 getStatusCode() == 200)                  {  
                    //  第3步:使用getEntity方法获得返回结果  
                    String result = EntityUtils.
 toString(httpResponse.getEntity());                      //  去掉返回结果中的"\r"字符,
 否则会在结果字符串后面显示一个小方格                      tvQueryResult.setText(result.replaceAll("\r", ""));  
                }  
                break;  
            //  提交HTTP POST请求  
            case R.id.btnPostQuery:  
                //  第1步:创建HttpPost对象  
                HttpPost httpPost = new HttpPost(url);  
                //  设置HTTP POST请求参数必须用NameValuePair对象  
                List<NameValuePair> params = new 
 ArrayList<NameValuePair>();                  params.add(new BasicNameValuePair
 ("bookname", etBookName.getText(). toString()));                  //  设置HTTP POST请求参数  
                httpPost.setEntity(new 
 UrlEncodedFormEntity(params, HTTP.UTF_8));                  //  第2步:使用execute方法发送HTTP 
 POST请求,并返回HttpResponse对象                  httpResponse = new DefaultHttpClient().
 execute(httpPost);                  if (httpResponse.getStatusLine().
 getStatusCode() == 200)                  {  
                    //  第3步:使用getEntity方法获得返回结果  
                    String result = EntityUtils.toString
 (httpResponse.getEntity());                      //  去掉返回结果中的"\r"字符,
 否则会在结果字符串后面显示一个小方格                      tvQueryResult.setText(result.replaceAll("\r", ""));  
                }  
                break;  
        }  
    }  
    catch (Exception e)  
    {  
        tvQueryResult.setText(e.getMessage());  
    }