您的位置:首页 > 理论基础 > 计算机网络

【Android进阶学习】Http编程之HttpClient

2012-03-11 19:05 405 查看
在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窗口就能看到输出的信息

package com.lingdududu.http;

import java.io.InputStream;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;

public class HttpGetActivity extends Activity {
String uri = "http://developer.android.com/";
final String TAG_STRING = "TAG";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

try {
//得到HttpClient对象
HttpClient getClient = new DefaultHttpClient();
//得到HttpGet对象
HttpGet request = new HttpGet(uri);
//客户端使用GET方式执行请教,获得服务器端的回应response
HttpResponse response = getClient.execute(request);
//判断请求是否成功
if(response.getStatusLine().getStatusCode()==HttpStatus.SC_OK){
Log.i(TAG_STRING, "请求服务器端成功");
//获得输入流
InputStream  inStrem = response.getEntity().getContent();
int result = inStrem.read();
while (result != -1){
System.out.print((char)result);
result = inStrem.read();
}
//关闭输入流
inStrem.close();
}else {
Log.i(TAG_STRING, "请求服务器端失败");
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

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

2.使用HttpClient来执行POST调用

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

package com.androidbook.services.httppost;

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

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

import android.app.Activity;
import android.os.Bundle;

public class HttpPostActivity extends Activity {
String uri = "http://developer.android.com/";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

BufferedReader in = null;
try {
HttpClient client = new DefaultHttpClient();
HttpPost request = new HttpPost("http://code.google.com/android/");
//使用NameValuePair来保存要传递的Post参数
List<NameValuePair> postParameters = new ArrayList<NameValuePair>();
//添加要传递的参数
postParameters.add(new BasicNameValuePair("id", "12345"));
postParameters.add(new BasicNameValuePair("username", "dave"));
//实例化UrlEncodedFormEntity对象
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(
postParameters);

//使用HttpPost对象来设置UrlEncodedFormEntity的Entity
request.setEntity(formEntity);
HttpResponse response = client.execute(request);
in = new BufferedReader(
new InputStreamReader(
response.getEntity().getContent()));

StringBuffer string = new StringBuffer("");
String lineStr = "";
while ((lineStr = in.readLine()) != null) {
string.append(lineStr + "\n");
}
in.close();

String resultStr = string.toString();
System.out.println(resultStr);
} catch(Exception e) {
// Do something about exceptions
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}


本文出自 “IT的点点滴滴” 博客,请务必保留此出处http://liangruijun.blog.51cto.com/3061169/803097
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: