HttpGet/HttpPost/HttpClient介绍

在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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

george0318

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值