android http

时间:2025-03-19 13:35:31

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

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

2.使用HttpClient来执行POST调用

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

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