博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
HttpClient使用详解
阅读量:7082 次
发布时间:2019-06-28

本文共 13088 字,大约阅读时间需要 43 分钟。

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

一、简介

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

下载地址: 

二、特性

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. 释放连接。无论执行方法是否成功,都必须释放连接

以上理论资料总结参考:

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

个人整理一份

 结果封装类 封装响应的头部信息、状态信息、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
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
getHeaders() { 75 return headerAll; 76 } 77 78 /** 79 * 设置结果头部信息 80 * 81 * @param headers 82 */ 83 public void setHeaders(Header[] headers) { 84 headerAll = new HashMap
(); 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 httpEntity103 */104 public void setHttpEntity(HttpEntity httpEntity) {105 this.httpEntity = httpEntity;106 }107 108 /**109 * 将服务器返回的结果HttpEntity流转换成String格式的内容110 * 111 * @param encoding112 * 指定的转换编码113 * @return114 */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() != null122 && 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=new137 // 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
headers, Map
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
headers, Map
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
headers, Map
params, String encoding) 86 throws ClientProtocolException, IOException { 87 HttpPost post = new HttpPost(url); 88 89 List
list = new ArrayList
(); 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 headers112 * @return113 */114 public static Header[] assemblyHeader(Map
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 * 组装Cookie126 * 127 * @param cookies128 * @return129 */130 public static String assemblyCookie(List
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 parameters144 * @return145 */146 public static String assemblyParameter(Map
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 demo155 public static void main(String[] args) {156 Map
param = new HashMap
();157 try {158 Result result = SendRequest.sendGet("http://www.baidu.com", param, param, "utf-8");159 // SendRequest.u160 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
param = new HashMap
(); 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 }
返回结果:

 

转载于:https://www.cnblogs.com/visec479/p/4820968.html

你可能感兴趣的文章
漏洞预警:WordPress 储存型 XSS 漏洞
查看>>
RTP封装h264
查看>>
BYOD:浮躁的名词背后我们不知道的事情
查看>>
Android 7.0之访问文件的权限和FileProvider类
查看>>
安卓selinux权限修改(基于tiny4412开发板)
查看>>
Web前端和后端之区分,以及…
查看>>
前端(第一节课 HTML、CSS 、JAVAscript的概念)
查看>>
Google Interview University - 坚持完成这套学习手册,你就可以去 Google 面试了
查看>>
<Linux性能调优指南>主要思路流程
查看>>
让天下没有难做的研发效能,云效金牌合作伙伴亮相云栖大会
查看>>
C语言实现一个列表式的学生信息管理系统(完善)
查看>>
从拒绝到拥抱 企业经历云安全的六个阶段
查看>>
对话华途“少帅” 深耕数据安全市场
查看>>
IDC:商业分析服务加速行业布局 与大数据结合紧密
查看>>
《数学与泛型编程:高效编程的奥秘》一第3章 古希腊的数论
查看>>
新西兰发明新型传感器,电子产品不再需要充电器
查看>>
IDC:2017年竞争和工作负载变革将改变供应链生态系统
查看>>
万国数据:“为了全方位保障混合云数据中心的安全,我们连猫都养了十只。”...
查看>>
移动金融2.0时代来临 “业务优化 +”平台成为趋势
查看>>
ssh使用无密码登陆
查看>>