a) 环境准备
· 从apache下载httpClient;
· 解压、将lib下的jar导入工程;
b) 几个主要类解释
类名 | 作用 |
HttpClient | HttpClient代表了一个http的客户端,HttpClient接口定义了大多数基本的http请求执行行为. |
HttpEntity | entity是发送或者接收消息的载体。entities 可以通过request和response获取到. |
HttpConnection | HttpConnection代表了一个http连接。 |
c) 第一个程序
说明: 用get方法访问www.baidu.com并返回内容 Code: |
Testing Code: //创建默认的httpClient实例. HttpClient httpclient = new DefaultHttpClient(); try { //创建httpget. HttpGet httpget = new HttpGet("http://www.baidu.com/"); System.out.println("executing request " + httpget.getURI()); //执行get请求. HttpResponse response = httpclient.execute(httpget); //获取响应实体 HttpEntity entity = response.getEntity(); System.out.println("--------------------------------------"); //打印响应状态 System.out.println(response.getStatusLine()); if (entity != null) { //打印响应内容长度 System.out.println("Response content length: " + entity.getContentLength()); //打印响应内容 System.out.println("Response content: " + EntityUtils.toString(entity)); } System.out.println("------------------------------------"); } finally { //关闭连接,释放资源 httpclient.getConnectionManager().shutdown(); }
|
输出: executing request http://www.baidu.com/ ---------------------------------------- HTTP/1.1 200 OK Response content length: 6759 Response content: <!doctype html><html><head><meta http-equiv="Content-Type" content="text/html;charset=gb2312"><title>百度一下,你就知道 </title>…(此处省略打印信息) ----------------------------------------- |