Apache提供HttpClient,它对java.net中的类做了封装和抽象,更适合在Android上开发应用。
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 request = new HttpGet(url);
HttpClient client = new DefaultHttpClient();
HttpResponse response = client.execute(request);
if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
String data = EntityUtils.toString(response.getEntity());
}
// 示例代码:HttpPost –> HttpClient –> HttpResponse
Post方式情况下,需要使用NameValuePair来保存要传递的参数,具体可以使用BasicNameValuePair,然后通过add方法添加到NameValuePair中。
String url = “http://www.txrj.com/reg.jsp”;
HttpPost request = new HttpPost(url);
// 添加参数
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair(“name”,"jake”));
// 设置字符集
HttpEntity entity = new UrlEncodedFormEntity(params, “gb2312”);
request.setEntity(entity);
HttpClient client = new DefaultHttpClient();
HttpResponse response = client.execute(request);
if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
String data = EntityUtils.toString(response.getEntity());
}