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());
}