HTTPClient


HttpClient应用开发几个类:

1. ClientConnectionManager是客户端连接管理器的接口,

提供以下几个抽象方法:

closeIdleConnections, 关闭空闲的连接

releaseConnection, 释放一个连接

requestConnection, 请求一个新的连接

shutdown 关闭ClientConnectionManager并释放资源

2. DefaultHttpClient是一个默认的Http客户端,可以用来创建一个http连接。

HttpClient httpClient = new DefaultHttpClient();

3. HttpResponse是一个http连接响应

HttpResponse response = httpClient.execute(httpRequest);

if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK)

 

//  示例代码:HttpGet –> HttpClient –> HttpResponse

String url = “http://www.txrj.com/reg.jsp?name=jake”;

HttpGet httpGet= new HttpGet(url); //HttpGet相当于http的get请求;

HttpClient client = new DefaultHttpClient(); //HttpClient是Http网络访问接口,和HttpURLConnection很像

HttpResponse response = client.execute(httpGet); //调用HttpClient的执行方法:execute();,返回一个HttpResponse

if(response.getStatusLine().getStatusCode() == 200) { //调用此方法与响应码相比较,是否等于200。这个200的意思是服务器成功响应客    户端的请求

HttpEntity httpEntity=  response .getEntity(); //调用HttpResponse的getEntity()方法,得到服务器返回的内容,返回的是一个   String data=EntityUtils.toString(httpEntity);    HttpEntity的实例,然后调用EntityUtils.toString这个静态方法

    把HttpEntity转换成字符串

}

 

// 示例代码:HttpPost –> HttpClient –> HttpResponse

Post方式情况下,需要使用NameValuePair来保存要传递的参数,具体可以使用BasicNameValuePair,然后通过add方法添加到NameValuePair中。

String url = “http://www.txrj.com/reg.jsp”;

HttpPost httpPost= new HttpPost(url);

request 

// 添加参数

List<NameValuePair> params = new ArrayList<NameValuePair>();

params.add(new BasicNameValuePair(“username”,"admin”));

params.add(new BasicNameValuePair("password","123456"));

// 设置字符集

HttpEntity entity = new UrlEncodedFormEntity(params, “utf-8”);

httpPost.setEntity(entity);

HttpClient client = new DefaultHttpClient();

HttpResponse response = client.execute(httpPost);

if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {

  String data = EntityUtils.toString(response.getEntity());

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值