HttpClient使用详解

Http协议的重要性相信不用我多说了,HttpClient相比传统JDK自带的URLConnection,增加了易用性和灵活性(具体区别,日后我们再讨论),它不仅是客户端发送Http请求变得容易,而且也方便了开发人员测试接口(基于Http协议的),即提高了开发的效率,也方便提高代码的健壮性。因此熟练掌握HttpClient是很重要的必修内容,掌握HttpClient后,相信对于Http协议的了解会更加深入。

一、简介

HttpClient是Apache Jakarta Common下的子项目,用来提供高效的、最新的、功能丰富的支持HTTP协议的客户端编程工具包,并且它支持HTTP协议最新的版本和建议。HttpClient已经应用在很多的项目中,比如Apache Jakarta上很著名的另外两个开源项目Cactus和HTMLUnit都使用了HttpClient。

下载地址: http://hc.apache.org/downloads.cgi

二、特性

1. 基于标准、纯净的java语言。实现了Http1.0和Http1.1

2. 以可扩展的面向对象的结构实现了Http全部的方法(GET, POST, PUT, DELETE, HEAD, OPTIONS, and TRACE)。

3. 支持HTTPS协议。

4. 通过Http代理建立透明的连接。

5. 利用CONNECT方法通过Http代理建立隧道的https连接。

6. Basic, Digest, NTLMv1, NTLMv2, NTLM2 Session, SNPNEGO/Kerberos认证方案。

7. 插件式的自定义认证方案。

8. 便携可靠的套接字工厂使它更容易的使用第三方解决方案。

9. 连接管理器支持多线程应用。支持设置最大连接数,同时支持设置每个主机的最大连接数,发现并关闭过期的连接。

10. 自动处理Set-Cookie中的Cookie。

11. 插件式的自定义Cookie策略。

12. Request的输出流可以避免流中内容直接缓冲到socket服务器。

13. Response的输入流可以有效的从socket服务器直接读取相应内容。

14. 在http1.0和http1.1中利用KeepAlive保持持久连接。

15. 直接获取服务器发送的response code和 headers。

16. 设置连接超时的能力。

17. 实验性的支持http1.1 response caching。

18. 源代码基于Apache License 可免费获取。

三、使用方法

使用HttpClient发送请求、接收响应很简单,一般需要如下几步即可。

1. 创建HttpClient对象。

2. 创建请求方法的实例,并指定请求URL。如果需要发送GET请求,创建HttpGet对象;如果需要发送POST请求,创建HttpPost对象。

3. 如果需要发送请求参数,可调用HttpGet、HttpPost共同的setParams(HetpParams params)方法来添加请求参数;对于HttpPost对象而言,也可调用setEntity(HttpEntity entity)方法来设置请求参数。

4. 调用HttpClient对象的execute(HttpUriRequest request)发送请求,该方法返回一个HttpResponse。

5. 调用HttpResponse的getAllHeaders()、getHeaders(String name)等方法可获取服务器的响应头;调用HttpResponse的getEntity()方法可获取HttpEntity对象,该对象包装了服务器的响应内容。程序可通过该对象获取服务器的响应内容。

6. 释放连接。无论执行方法是否成功,都必须释放连接

以上理论资料总结参考:

http://blog.csdn.net/wangpeng047/article/details/19624529

但是上诉地址中的代码实例并不精简:

个人整理一份

 结果封装类 封装响应的头部信息、状态信息、Cookie信息、返回内容
  1  import java.io.BufferedInputStream;
  2 import java.io.ByteArrayOutputStream;
  3 import java.io.IOException;
  4 import java.io.InputStream;
  5 import java.util.HashMap;
  6 import java.util.zip.GZIPInputStream;
  7 
  8 import org.apache.http.Header;
  9 import org.apache.http.HttpEntity;
 10 import org.apache.http.util.EntityUtils;
 11 import org.apache.log4j.Logger;
 12 /**
 13  * 
 14  * 结果封装类 封装响应的头部信息、状态信息、Cookie信息、返回内容
 15  * 
 16  * @author lishangzhi 
 17  *           E-mail:1669852599@qq.com
 18  * @version v1.0
 19  *           Time:2015年8月1日 上午9:45:33
 20  */
 21 public class Result {
 22     /**
 23      * Logger for this class
 24      */
 25     private static final Logger logger = Logger.getLogger(Result.class);
 26 
 27     private String cookie;
 28     private int statusCode;
 29     private HashMap<String, Header> headerAll;
 30     private HttpEntity httpEntity;
 31     private String otherContent;
 32 
 33     /**
 34      * 获取Cookie信息
 35      * 
 36      * @return
 37      */
 38     public String getCookie() {
 39         return cookie;
 40     }
 41 
 42     /**
 43      * 设置Cookie信息
 44      * 
 45      * @param cookie
 46      */
 47     public void setCookie(String cookie) {
 48         this.cookie = cookie;
 49     }
 50 
 51     /**
 52      * 获取结果状态码
 53      * 
 54      * @return
 55      */
 56     public int getStatusCode() {
 57         return statusCode;
 58     }
 59 
 60     /**
 61      * 设置结果状态码
 62      * 
 63      * @param statusCode
 64      */
 65     public void setStatusCode(int statusCode) {
 66         this.statusCode = statusCode;
 67     }
 68 
 69     /**
 70      * 获取结果头部信息
 71      * 
 72      * @return
 73      */
 74     public HashMap<String, Header> getHeaders() {
 75         return headerAll;
 76     }
 77 
 78     /**
 79      * 设置结果头部信息
 80      * 
 81      * @param headers
 82      */
 83     public void setHeaders(Header[] headers) {
 84         headerAll = new HashMap<String, Header>();
 85         for (Header header : headers) {
 86             headerAll.put(header.getName(), header);
 87         }
 88     }
 89 
 90     /**
 91      * 获取响应结果
 92      * 
 93      * @return
 94      */
 95     public HttpEntity getHttpEntity() {
 96         return httpEntity;
 97     }
 98 
 99     /**
100      * 设置响应结果
101      * 
102      * @param httpEntity
103      */
104     public void setHttpEntity(HttpEntity httpEntity) {
105         this.httpEntity = httpEntity;
106     }
107 
108     /**
109      * 将服务器返回的结果HttpEntity流转换成String格式的内容
110      * 
111      * @param encoding
112      *            指定的转换编码
113      * @return
114      */
115     public String getHtmlContent(String encoding) {
116         // HTML内容
117         if (httpEntity != null) {
118             ByteArrayOutputStream output = new ByteArrayOutputStream();
119             InputStream is = null;
120             try {
121                 if (httpEntity.getContentEncoding() != null
122                         && httpEntity.getContentEncoding().getValue().indexOf("gzip") != -1) {
123                     // GZIP格式的流解压
124                     is = new GZIPInputStream(new BufferedInputStream(httpEntity.getContent()));
125                 } else {
126                     is = new BufferedInputStream(httpEntity.getContent());
127                 }
128                 String responseContent = "";
129                 if (is != null) {
130                     byte[] buffer = new byte[1024];
131                     int n;
132                     while ((n = is.read(buffer)) >= 0) {
133                         output.write(buffer, 0, n);
134                     }
135                     responseContent = output.toString(encoding);
136                     // responseContent=new
137                     // String(responseContent.getBytes("utf-8"),"gbk");
138                 }
139                 return responseContent;
140             } catch (IllegalStateException e) {
141                 e.printStackTrace();
142                 return "";
143             } catch (IOException e) {
144                 e.printStackTrace();
145                 return "";
146             }
147         } else {
148             return "";
149         }
150     }
151 
152     /**
153      * 获取请求中的内容
154      */
155     public String getHtml(Result result, String chart) {
156         logger.debug("getHtml(Result, String) - start"); //$NON-NLS-1$
157 
158         HttpEntity entity = result.getHttpEntity();
159         String resultStr = "";
160         try {
161             resultStr = EntityUtils.toString(entity, chart);
162         } catch (Exception e) {
163             logger.error("getHtml(Result, String)", e); //$NON-NLS-1$
164 
165             // e.printStackTrace();
166         } finally {
167             try {
168                 EntityUtils.consume(entity);
169             } catch (IOException e) {
170                 logger.error("getHtml(Result, String)", e); //$NON-NLS-1$
171 
172                 // e.printStackTrace();
173             }
174         }
175 
176         logger.debug("getHtml(Result, String) - end"); //$NON-NLS-1$
177         return resultStr;
178     }
179 
180     /**
181      * 关闭HttpEntity流
182      */
183     public void consume(Result result) {
184         try {
185             HttpEntity entity = result.getHttpEntity();
186             // EntityUtils.consume(entity);
187             if (entity.isStreaming()) {
188                 InputStream instream = entity.getContent();
189                 if (instream != null) {
190                     instream.close();
191                 }
192             }
193         } catch (IOException e) {
194             e.printStackTrace();
195         }
196     }
197 
198     public String getOtherContent() {
199         return otherContent;
200     }
201 
202     public void setOtherContent(String otherContent) {
203         this.otherContent = otherContent;
204     }
205 }
发送请求 httpclient封装

  1 import java.io.IOException;
  2 import java.util.ArrayList;
  3 import java.util.HashMap;
  4 import java.util.List;
  5 import java.util.Map;
  6 import org.apache.http.Header;
  7 import org.apache.http.HttpEntity;
  8 import org.apache.http.HttpResponse;
  9 import org.apache.http.NameValuePair;
 10 import org.apache.http.client.ClientProtocolException;
 11 import org.apache.http.client.entity.UrlEncodedFormEntity;
 12 import org.apache.http.client.methods.HttpGet;
 13 import org.apache.http.client.methods.HttpPost;
 14 import org.apache.http.cookie.Cookie;
 15 import org.apache.http.impl.client.DefaultHttpClient;
 16 import org.apache.http.message.BasicHeader;
 17 import org.apache.http.message.BasicNameValuePair;
 18 /**
 19  * 
 20  * 发送请求 httpclient封装
 21  * 
 22  * @author lishangzhi 
 23  *           E-mail:1669852599@qq.com
 24  * @version v1.0
 25  *           Time:2015年8月1日 上午9:46:07
 26  */
 27 @SuppressWarnings("deprecation")
 28 public class SendRequest {
 29 
 30     private static DefaultHttpClient client = new DefaultHttpClient();
 31 
 32     /**
 33      * 发送Get请求
 34      * 
 35      * @param url
 36      *            请求的地址
 37      * @param headers
 38      *            请求的头部信息
 39      * @param params
 40      *            请求的参数
 41      * @param encoding
 42      *            字符编码
 43      * @return
 44      * @throws ClientProtocolException
 45      * @throws IOException
 46      */
 47     public static Result sendGet(String url, Map<String, String> headers, Map<String, String> params, String encoding,
 48             boolean duan) throws ClientProtocolException, IOException {
 49         url = url + (null == params ? "" : assemblyParameter(params));
 50         HttpGet hp = new HttpGet(url);
 51         if (null != headers)
 52             hp.setHeaders(assemblyHeader(headers));
 53         HttpResponse response = client.execute(hp);
 54         if (duan)
 55             hp.abort();
 56         HttpEntity entity = response.getEntity();
 57         Result result = new Result();
 58         result.setCookie(assemblyCookie(client.getCookieStore().getCookies()));
 59         result.setStatusCode(response.getStatusLine().getStatusCode());
 60         result.setHeaders(response.getAllHeaders());
 61         result.setHttpEntity(entity);
 62         return result;
 63     }
 64 
 65     public static Result sendGet(String url, Map<String, String> headers, Map<String, String> params, String encoding)
 66             throws ClientProtocolException, IOException {
 67         return sendGet(url, headers, params, encoding, false);
 68     }
 69 
 70     /**
 71      * 发送Post请求
 72      * 
 73      * @param url
 74      *            请求的地址
 75      * @param headers
 76      *            请求的头部信息
 77      * @param params
 78      *            请求的参数
 79      * @param encoding
 80      *            字符编码
 81      * @return
 82      * @throws ClientProtocolException
 83      * @throws IOException
 84      */
 85     public static Result sendPost(String url, Map<String, String> headers, Map<String, String> params, String encoding)
 86             throws ClientProtocolException, IOException {
 87         HttpPost post = new HttpPost(url);
 88 
 89         List<NameValuePair> list = new ArrayList<NameValuePair>();
 90         for (String temp : params.keySet()) {
 91             list.add(new BasicNameValuePair(temp, params.get(temp)));
 92         }
 93         post.setEntity(new UrlEncodedFormEntity(list, encoding));
 94 
 95         if (null != headers)
 96             post.setHeaders(assemblyHeader(headers));
 97         HttpResponse response = client.execute(post);
 98         HttpEntity entity = response.getEntity();
 99 
100         Result result = new Result();
101         result.setStatusCode(response.getStatusLine().getStatusCode());
102         result.setHeaders(response.getAllHeaders());
103         result.setCookie(assemblyCookie(client.getCookieStore().getCookies()));
104         result.setHttpEntity(entity);
105         return result;
106     }
107 
108     /**
109      * 组装头部信息
110      * 
111      * @param headers
112      * @return
113      */
114     public static Header[] assemblyHeader(Map<String, String> headers) {
115         Header[] allHeader = new BasicHeader[headers.size()];
116         int i = 0;
117         for (String str : headers.keySet()) {
118             allHeader[i] = new BasicHeader(str, headers.get(str));
119             i++;
120         }
121         return allHeader;
122     }
123 
124     /**
125      * 组装Cookie
126      * 
127      * @param cookies
128      * @return
129      */
130     public static String assemblyCookie(List<Cookie> cookies) {
131         StringBuffer sbu = new StringBuffer();
132         for (Cookie cookie : cookies) {
133             sbu.append(cookie.getName()).append("=").append(cookie.getValue()).append(";");
134         }
135         if (sbu.length() > 0)
136             sbu.deleteCharAt(sbu.length() - 1);
137         return sbu.toString();
138     }
139 
140     /**
141      * 组装请求参数
142      * 
143      * @param parameters
144      * @return
145      */
146     public static String assemblyParameter(Map<String, String> parameters) {
147         String para = "?";
148         for (String str : parameters.keySet()) {
149             para += str + "=" + parameters.get(str) + "&";
150         }
151         return para.substring(0, para.length() - 1);
152     }
153 
154     // TODO demo
155     public static void main(String[] args) {
156         Map<String, String> param = new HashMap<String, String>();
157         try {
158             Result result = SendRequest.sendGet("http://www.baidu.com", param, param, "utf-8");
159             // SendRequest.u
160             String str = result.getHtml(result, "utf-8");
161             System.out.println(str);
162         } catch (Exception e) {
163             e.printStackTrace();
164         }
165     }
166 
167 }
测试案例:
 1 // TODO demo
 2     public static void main(String[] args) {
 3         Map<String, String> param = new HashMap<String, String>();
 4         try {
 5             Result result = SendRequest.sendGet("http://www.baidu.com", param, param, "utf-8");
 6             // SendRequest.u
 7             String str = result.getHtml(result, "utf-8");
 8             System.out.println(str);
 9         } catch (Exception e) {
10             e.printStackTrace();
11         }
12     }
返回结果:

 

posted @ 2015-09-19 09:57  小码哥、iByte  阅读(15762)  评论(0编辑  收藏  举报