Android Http编程之HttpClient

来源:互联网 发布:淘宝95小嫩模全集 编辑:程序博客网 时间:2024/04/29 20:21

 在Android开发中,Android SDK附带了Apache的HttpClient,它是一个完善的客户端。它提供了对HTTP协议的全面支持,可以使用HttpClient的对象来执行HTTP GET和HTTP POST调用。

HTTP工作原理:

1.客户端(一般是指浏览器,这里是指自己写的程序)与服务器建立连接

2.建立连接后,客户端向服务器发送请求

3.服务器接收到请求后,向客户端发送响应信息

4.客户端与服务器断开连接

HttpClient的一般使用步骤:

1.使用DefaultHttpClient类实例化HttpClient对象

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

3.调用execute方法发送HTTP GET或HTTP POST请求,并返回HttpResponse对象。

4.通过HttpResponse接口的getEntity方法返回响应信息,并进行相应的处理。

最后记得要在AndroidManifest.xml文件添加网络权限

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

 下面是具体的例子:

1.使用HttpClient来执行GET调用

在LogCat窗口就能看到输出的信息

  1. package com.lingdududu.http;  
  2.  
  3. import java.io.InputStream;  
  4.  
  5. import org.apache.http.HttpResponse;  
  6. import org.apache.http.HttpStatus;  
  7. import org.apache.http.client.HttpClient;  
  8. import org.apache.http.client.methods.HttpGet;  
  9. import org.apache.http.impl.client.DefaultHttpClient;  
  10.  
  11. import android.app.Activity;  
  12. import android.os.Bundle;  
  13. import android.util.Log;  
  14.  
  15. public class HttpGetActivity extends Activity {  
  16.     String uri = "http://developer.android.com/";  
  17.     final String TAG_STRING = "TAG";  
  18.     @Override 
  19.     public void onCreate(Bundle savedInstanceState) {  
  20.         super.onCreate(savedInstanceState);  
  21.         setContentView(R.layout.main);  
  22.           
  23.         try {  
  24.             //得到HttpClient对象  
  25.             HttpClient getClient = new DefaultHttpClient();  
  26.             //得到HttpGet对象  
  27.             HttpGet request = new HttpGet(uri);  
  28.             //客户端使用GET方式执行请教,获得服务器端的回应response  
  29.             HttpResponse response = getClient.execute(request);  
  30.             //判断请求是否成功    
  31.             if(response.getStatusLine().getStatusCode()==HttpStatus.SC_OK){  
  32.                 Log.i(TAG_STRING, "请求服务器端成功");  
  33.                 //获得输入流  
  34.                 InputStream  inStrem = response.getEntity().getContent();  
  35.                 int result = inStrem.read();  
  36.                 while (result != -1){  
  37.                     System.out.print((char)result);  
  38.                     result = inStrem.read();  
  39.                 }  
  40.                 //关闭输入流  
  41.                 inStrem.close();      
  42.             }else {  
  43.                 Log.i(TAG_STRING, "请求服务器端失败");  
  44.             }             
  45.         } catch (Exception e) {  
  46.             // TODO Auto-generated catch block  
  47.             e.printStackTrace();  
  48.         }  
  49.     }  

使用HTTP GET调用有一个缺点就是,请求的参数作为URL一部分来传递,以这种方式传递的时候,URL的长度应该在2048个字符之内。如果超出这个这范围,就要使用到HTTP POST调用。

2.使用HttpClient来执行POST调用

 使用POST调用进行参数传递时,需要使用NameValuePair来保存要传递的参数。NameValuePair封装了一个键/值组合。另外,还需要设置所使用的字符集。

  1. package com.androidbook.services.httppost;  
  2.  
  3. import java.io.BufferedReader;  
  4. import java.io.IOException;  
  5. import java.io.InputStreamReader;  
  6. import java.util.ArrayList;  
  7. import java.util.List;  
  8.  
  9. import org.apache.http.HttpResponse;  
  10. import org.apache.http.NameValuePair;  
  11. import org.apache.http.client.HttpClient;  
  12. import org.apache.http.client.entity.UrlEncodedFormEntity;  
  13. import org.apache.http.client.methods.HttpPost;  
  14. import org.apache.http.impl.client.DefaultHttpClient;  
  15. import org.apache.http.message.BasicNameValuePair;  
  16.  
  17. import android.app.Activity;  
  18. import android.os.Bundle;  
  19.  
  20. public class HttpPostActivity extends Activity {  
  21.     String uri = "http://developer.android.com/";  
  22.     @Override 
  23.     public void onCreate(Bundle savedInstanceState) {  
  24.         super.onCreate(savedInstanceState);  
  25.         setContentView(R.layout.main);  
  26.  
  27.         BufferedReader in = null;  
  28.         try {  
  29.             HttpClient client = new DefaultHttpClient();  
  30.             HttpPost request = new HttpPost("http://code.google.com/android/");  
  31.             //使用NameValuePair来保存要传递的Post参数  
  32.             List<NameValuePair> postParameters = new ArrayList<NameValuePair>();  
  33.             //添加要传递的参数    
  34.             postParameters.add(new BasicNameValuePair("id""12345"));  
  35.             postParameters.add(new BasicNameValuePair("username""dave"));  
  36.             //实例化UrlEncodedFormEntity对象  
  37.             UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(  
  38.                     postParameters);  
  39.  
  40.             //使用HttpPost对象来设置UrlEncodedFormEntity的Entity  
  41.             request.setEntity(formEntity);  
  42.             HttpResponse response = client.execute(request);  
  43.             in = new BufferedReader(  
  44.                     new InputStreamReader(  
  45.                             response.getEntity().getContent()));  
  46.  
  47.             StringBuffer string = new StringBuffer("");  
  48.             String lineStr = "";  
  49.             while ((lineStr = in.readLine()) != null) {  
  50.                 string.append(lineStr + "\n");  
  51.             }  
  52.             in.close();  
  53.  
  54.             String resultStr = string.toString();  
  55.             System.out.println(resultStr);  
  56.         } catch(Exception e) {  
  57.             // Do something about exceptions  
  58.         } finally {  
  59.             if (in != null) {  
  60.                 try {  
  61.                     in.close();  
  62.                 } catch (IOException e) {  
  63.                     e.printStackTrace();  
  64.                 }  
  65.             }  
  66.         }  
  67.     }  
0 0
原创粉丝点击