在Android中完全可以使用HttpGet/HttpPost/HttpClient对HttpURLConnection进行替换,并且完全比HttpURLConnection好用,特别实在处理Session/Cookie等细节问题。我们可以将他们形象的理解为:
HttpClient可看作是一个浏览器
HttpPost一个Post请求
HttpGet一个Get请求
HttpClient.execute(HttpGet/HttpPost)相当于在浏览器中输入一段路径进行访问
HttpResponse http的一个响应
HttpEntity一个实体对象
对于Get请求而言,只有客户端的代码new HttpGet(url),将请求数据写在url中。
对于Post请求而言,NameValuePair封装成list,再封装成HttpEntity用于向服务器端传参数;
开发步骤及示例代码:
在客户端发送Get请求:
// 1. 创建HttpClient对象(HttpClient mHttpClient = new DefaultHttpClient();)
// 2. 构建Get请求
// 3. 发送Get请求(mHttpClient.execute(req);)
// 4. 获取返回的HttpResponse对象,并获取其中的内容(InputStream is =
// rsp.getEntity().getContent();)
// 发送http Get请求,注意需要使用网络权限, 以及该方法不可以在UI线程执行
public static HttpResponse doGet(String url) {
HttpResponse mHttpResponse = null;
// 创建HttpClient,Http请求由该对象发出
HttpClient mHttpClient = new DefaultHttpClient();
// 设置连接超时,10sm没有响应表示超时
mHttpClient.getParams().setParameter(
CoreConnectionPNames.CONNECTION_TIMEOUT, 10000);
// 构建get请求命令
HttpGet req = new HttpGet(url);
// 发送请求
try {
mHttpResponse = mHttpClient.execute(req);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.e(“FSLog”, e.toString());
}
return mHttpResponse;
}
在客户端发送Post请求,发送参数到servlet,并获取servlet返回的数据
// 1. 创建HttpClient对象(HttpClient mHttpClient = new DefaultHttpClient();)
// 2. 创建post请求
// 3. 创建要发送的参数列表(ArrayList dataList = new
// ArrayList();)
// 4. 配置参数列表(req.setEntity(new UrlEncodedFormEntity(dataList ));)
// 5. 发送post请求(mHttpClient.execute(req);)
// 6. 获取返回的HttpResponse对象,并获取其中的内容(InputStream is =
// rsp.getEntity().getContent();)
// 发送http Post请求,同时将传递参数
public static HttpResponse doPost(String url,
ArrayList<NameValuePair> params) {
HttpResponse mHttpResponse = null;
// 创建HttpClient,Http请求由该对象发出
HttpClient mHttpClient = new DefaultHttpClient();
// 设置连接超时,10sm没有响应表示超时
mHttpClient.getParams().setParameter(
CoreConnectionPNames.CONNECTION_TIMEOUT, 10000);
// 构建get请求命令
HttpPost req = new HttpPost(url);
// 发送请求
try {
// 设置随post发送的键值对,将params装换成entity对象,打包到req中一起发出
req.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
mHttpResponse = mHttpClient.execute(req);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.e("FSLog", e.toString());
}
return mHttpResponse;
}