操作HttpClient时的一个工具类,使用是HttpClient4.5.2

  1. package com.xxxx.charactercheck.utils;
  2.  
  3. import java.io.File;
  4. import java.io.IOException;
  5. import java.net.URL;
  6. import java.util.ArrayList;
  7. import java.util.List;
  8. import java.util.Map;
  9.  
  10. import org.apache.http.HttpEntity;
  11. import org.apache.http.NameValuePair;
  12. import org.apache.http.client.config.RequestConfig;
  13. import org.apache.http.client.entity.UrlEncodedFormEntity;
  14. import org.apache.http.client.methods.CloseableHttpResponse;
  15. import org.apache.http.client.methods.HttpGet;
  16. import org.apache.http.client.methods.HttpPost;
  17. import org.apache.http.conn.ssl.DefaultHostnameVerifier;
  18. import org.apache.http.conn.util.PublicSuffixMatcher;
  19. import org.apache.http.conn.util.PublicSuffixMatcherLoader;
  20. import org.apache.http.entity.ContentType;
  21. import org.apache.http.entity.StringEntity;
  22. import org.apache.http.entity.mime.MultipartEntityBuilder;
  23. import org.apache.http.entity.mime.content.FileBody;
  24. import org.apache.http.entity.mime.content.StringBody;
  25. import org.apache.http.impl.client.CloseableHttpClient;
  26. import org.apache.http.impl.client.HttpClients;
  27. import org.apache.http.message.BasicNameValuePair;
  28. import org.apache.http.util.EntityUtils;
  29.  
  30. public class HttpClientUtil {
  31. private RequestConfig requestConfig = RequestConfig.custom()
  32. .setSocketTimeout(15000)
  33. .setConnectTimeout(15000)
  34. .setConnectionRequestTimeout(15000)
  35. .build();
  36.  
  37. private static HttpClientUtil instance = null;
  38. private HttpClientUtil(){}
  39. public static HttpClientUtil getInstance(){
  40. if (instance == null) {
  41. instance = new HttpClientUtil();
  42. }
  43. return instance;
  44. }
  45.  
  46. /**
  47. * 发送 post请求
  48. * @param httpUrl 地址
  49. */
  50. public String sendHttpPost(String httpUrl) {
  51. HttpPost httpPost = new HttpPost(httpUrl);// 创建httpPost
  52. return sendHttpPost(httpPost);
  53. }
  54.  
  55. /**
  56. * 发送 post请求
  57. * @param httpUrl 地址
  58. * @param params 参数(格式:key1=value1&key2=value2)
  59. */
  60. public String sendHttpPost(String httpUrl, String params) {
  61. HttpPost httpPost = new HttpPost(httpUrl);// 创建httpPost
  62. try {
  63. //设置参数
  64. StringEntity stringEntity = new StringEntity(params, "UTF-8");
  65. stringEntity.setContentType("application/x-www-form-urlencoded");
  66. httpPost.setEntity(stringEntity);
  67. } catch (Exception e) {
  68. e.printStackTrace();
  69. }
  70. return sendHttpPost(httpPost);
  71. }
  72.  
  73. /**
  74. * 发送 post请求
  75. * @param httpUrl 地址
  76. * @param maps 参数
  77. */
  78. public String sendHttpPost(String httpUrl, Map<String, String> maps) {
  79. HttpPost httpPost = new HttpPost(httpUrl);// 创建httpPost
  80. // 创建参数队列
  81. List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
  82. for (String key : maps.keySet()) {
  83. nameValuePairs.add(new BasicNameValuePair(key, maps.get(key)));
  84. }
  85. try {
  86. httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8"));
  87. } catch (Exception e) {
  88. e.printStackTrace();
  89. }
  90. return sendHttpPost(httpPost);
  91. }
  92.  
  93. /**
  94. * 发送 post请求(带文件)
  95. * @param httpUrl 地址
  96. * @param maps 参数
  97. * @param fileLists 附件
  98. */
  99. public String sendHttpPost(String httpUrl, Map<String, String> maps, List<File> fileLists) {
  100. HttpPost httpPost = new HttpPost(httpUrl);// 创建httpPost
  101. MultipartEntityBuilder meBuilder = MultipartEntityBuilder.create();
  102. for (String key : maps.keySet()) {
  103. meBuilder.addPart(key, new StringBody(maps.get(key), ContentType.TEXT_PLAIN));
  104. }
  105. for(File file : fileLists) {
  106. FileBody fileBody = new FileBody(file);
  107. meBuilder.addPart("files", fileBody);
  108. }
  109. HttpEntity reqEntity = meBuilder.build();
  110. httpPost.setEntity(reqEntity);
  111. return sendHttpPost(httpPost);
  112. }
  113.  
  114. /**
  115. * 发送Post请求
  116. * @param httpPost
  117. * @return
  118. */
  119. private String sendHttpPost(HttpPost httpPost) {
  120. CloseableHttpClient httpClient = null;
  121. CloseableHttpResponse response = null;
  122. HttpEntity entity = null;
  123. String responseContent = null;
  124. try {
  125. // 创建默认的httpClient实例.
  126. httpClient = HttpClients.createDefault();
  127. httpPost.setConfig(requestConfig);
  128. // 执行请求
  129. response = httpClient.execute(httpPost);
  130. entity = response.getEntity();
  131. responseContent = EntityUtils.toString(entity, "UTF-8");
  132. } catch (Exception e) {
  133. e.printStackTrace();
  134. } finally {
  135. try {
  136. // 关闭连接,释放资源
  137. if (response != null) {
  138. response.close();
  139. }
  140. if (httpClient != null) {
  141. httpClient.close();
  142. }
  143. } catch (IOException e) {
  144. e.printStackTrace();
  145. }
  146. }
  147. return responseContent;
  148. }
  149.  
  150. /**
  151. * 发送 get请求
  152. * @param httpUrl
  153. */
  154. public String sendHttpGet(String httpUrl) {
  155. HttpGet httpGet = new HttpGet(httpUrl);// 创建get请求
  156. return sendHttpGet(httpGet);
  157. }
  158.  
  159. /**
  160. * 发送 get请求Https
  161. * @param httpUrl
  162. */
  163. public String sendHttpsGet(String httpUrl) {
  164. HttpGet httpGet = new HttpGet(httpUrl);// 创建get请求
  165. return sendHttpsGet(httpGet);
  166. }
  167.  
  168. /**
  169. * 发送Get请求
  170. * @param httpPost
  171. * @return
  172. */
  173. private String sendHttpGet(HttpGet httpGet) {
  174. CloseableHttpClient httpClient = null;
  175. CloseableHttpResponse response = null;
  176. HttpEntity entity = null;
  177. String responseContent = null;
  178. try {
  179. // 创建默认的httpClient实例.
  180. httpClient = HttpClients.createDefault();
  181. httpGet.setConfig(requestConfig);
  182. // 执行请求
  183. response = httpClient.execute(httpGet);
  184. entity = response.getEntity();
  185. responseContent = EntityUtils.toString(entity, "UTF-8");
  186. } catch (Exception e) {
  187. e.printStackTrace();
  188. } finally {
  189. try {
  190. // 关闭连接,释放资源
  191. if (response != null) {
  192. response.close();
  193. }
  194. if (httpClient != null) {
  195. httpClient.close();
  196. }
  197. } catch (IOException e) {
  198. e.printStackTrace();
  199. }
  200. }
  201. return responseContent;
  202. }
  203.  
  204. /**
  205. * 发送Get请求Https
  206. * @param httpPost
  207. * @return
  208. */
  209. private String sendHttpsGet(HttpGet httpGet) {
  210. CloseableHttpClient httpClient = null;
  211. CloseableHttpResponse response = null;
  212. HttpEntity entity = null;
  213. String responseContent = null;
  214. try {
  215. // 创建默认的httpClient实例.
  216. PublicSuffixMatcher publicSuffixMatcher = PublicSuffixMatcherLoader.load(new URL(httpGet.getURI().toString()));
  217. DefaultHostnameVerifier hostnameVerifier = new DefaultHostnameVerifier(publicSuffixMatcher);
  218. httpClient = HttpClients.custom().setSSLHostnameVerifier(hostnameVerifier).build();
  219. httpGet.setConfig(requestConfig);
  220. // 执行请求
  221. response = httpClient.execute(httpGet);
  222. entity = response.getEntity();
  223. responseContent = EntityUtils.toString(entity, "UTF-8");
  224. } catch (Exception e) {
  225. e.printStackTrace();
  226. } finally {
  227. try {
  228. // 关闭连接,释放资源
  229. if (response != null) {
  230. response.close();
  231. }
  232. if (httpClient != null) {
  233. httpClient.close();
  234. }
  235. } catch (IOException e) {
  236. e.printStackTrace();
  237. }
  238. }
  239. return responseContent;
  240. }
  241. }

调用例子

  1. @ResponseBody
  2. @RequestMapping(value = "/check")
  3. public String check(
  4. Model model,
  5. HttpServletRequest request,
  6. HttpServletResponse response,
  7. String content) {
  8. try {
  9. String httpUrl = ExtendedServerConfig.getInstance().getStringProperty("httpUrl");
  10. Map<String, String> maps = new HashMap<String, String>();
  11. maps.put("content", content);
  12. maps.put("reserve_tag", ExtendedServerConfig.getInstance().getStringProperty("reserve_tag"));
  13. maps.put("user_key", ExtendedServerConfig.getInstance().getStringProperty("user_key"));
  14. maps.put("check_level", ExtendedServerConfig.getInstance().getStringProperty("check_level"));
  15. return HttpClientUtil.getInstance().sendHttpPost(httpUrl, maps);
  16. } catch (Exception e) {
  17. e.printStackTrace();
  18. }
  19. return null;
  20. }

HttpClient4.5.2调用示例(转载+原创)的更多相关文章

  1. [转载+原创]Emgu CV on C# (三) —— Emgu CV on 均衡化

    本文简要描述了均衡化原理及数学实现等理论问题,最终利用emgucv实现图像的灰度均衡. 直方图的均衡化,这是图像增强的常用方法. 一.均衡化原理及数学实现(转载) 均衡化原理及数学实现可重点参看——& ...

  2. 股票数据调用示例代码php

    <!--?php // +---------------------------------------------------------------------- // | JuhePHP ...

  3. Nginx 简单的负载均衡配置示例(转载)

    原文地址:Nginx 简单的负载均衡配置示例(转载) 作者:水中游于 www.s135.com 和 blog.s135.com 域名均指向 Nginx 所在的服务器IP. 用户访问http://www ...

  4. WebService核心文件【server-config.wsdd】详解及调用示例

    WebService核心文件[server-config.wsdd]详解及调用示例 作者:Vashon 一.准备工作 导入需要的jar包: 二.配置web.xml 在web工程的web.xml中添加如 ...

  5. Windows API 调用示例

    Ø  简介 本文主要记录 Windows API 的调用示例,因为这项技术并不常用,属于 C# 中比较孤僻或接触底层的技术,并不常用.但是有时候也可以借助他完成一些 C# 本身不能完成的功能,例如:通 ...

  6. C#中异步调用示例与详解

    using System; using System.Collections.Generic; using System.Text; using System.Runtime.InteropServi ...

  7. HTML 百度地图API调用示例源码

    <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content ...

  8. C#全能数据库操作类及调用示例

    C#全能数据库操作类及调用示例 using System; using System.Data; using System.Data.Common; using System.Configuratio ...

  9. 利用JavaScriptSOAPClient直接调用webService --完整的前后台配置与调用示例

    JavaScriptSoapClient下载地址:https://archive.codeplex.com/?p=javascriptsoapclient JavaScriptSoapClient的D ...

随机推荐

  1. Java Servlet 笔记1

    1. 什么是Servlet. Java Servlet 是运行在 Web 服务器或应用服务器上的程序,它是作为来自 Web 浏览器或其他 HTTP 客户端的请求和 HTTP 服务器上的数据库或应用程序 ...

  2. Linux下安装3.0以上的python

    Linux下自带的python2.7是不建议删除的,很多系统软件依赖python2.7,但是现在我们学习python一般需要python3.0,下面介绍安装python3.0. 1.进入python官 ...

  3. 第一次C语言作业

    1. 求圆的面积和周长 输入圆的半径,求圆的周长和面积 流程图 测试结果: 实验问题:1.加号输入到引号内部导致运算终止 解决办法:通过改正加号位置是算法正确并继续运行 2判断闰年 输入一个四位年份, ...

  4. Mac下安装PEAR

    The following instructions install PEAR and PECL on Mac OS X under/usr/local/. PECL is bundled with ...

  5. jQuery 遍历 – 祖先

    祖先是父.祖父或曾祖父等等. 通过 jQuery,您能够向上遍历 DOM 树,以查找元素的祖先. 向上遍历 DOM 树 这些 jQuery 方法很有用,它们用于向上遍历 DOM 树: parent() ...

  6. 记一个万金油开源框架JHipster

    本文地址:http://blog.csdn.net/sushengmiyan/article/details/53190236 百搭代码生成框架 体验新技术汇总: Spring Boot Spring ...

  7. java http post tomcat解除 长度限制

    1.    Get方法长度限制 Http Get方法提交的数据大小长度并没有限制,HTTP协议规范没有对URL长度进行限制.这个限制是特定的浏览器及服务器对它的限制. 如:IE对URL长度的限制是20 ...

  8. SQL Server 虚拟化(1)——虚拟化简介

    本文属于SQL Server虚拟化系列 前言: 现代系统中,虚拟化越来越普遍,如果缺乏对虚拟化工作原理的理解,那么DBA在解决性能问题比如降低资源争用.提高备份还原速度等操作时就会出现盲点.所以基于本 ...

  9. ubuntu初始化python3+postgresql+uwsgi+nginx+django

    一. postgresql 数据库 安装 apt-get update apt-get install postgresql 进入psql客户端 sudo -u postgres psql 创建数据库 ...

  10. Apache ActiveMQ实战(2)-集群

    ActiveMQ的集群 内嵌代理所引发的问题: 消息过载 管理混乱 如何解决这些问题--集群的两种方式: Master slave Broker clusters ActiveMQ的集群有两种方式: ...