HttpClientUtils.java 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317
  1. package com.wsm.common.util;
  2. import javax.net.ssl.SSLContext;
  3. import javax.net.ssl.SSLException;
  4. import javax.net.ssl.SSLSession;
  5. import javax.net.ssl.SSLSocket;
  6. import org.apache.commons.io.IOUtils;
  7. import org.apache.commons.lang.StringUtils;
  8. import org.apache.http.Consts;
  9. import org.apache.http.HttpEntity;
  10. import org.apache.http.HttpResponse;
  11. import org.apache.http.NameValuePair;
  12. import org.apache.http.client.HttpClient;
  13. import org.apache.http.client.config.RequestConfig;
  14. import org.apache.http.client.config.RequestConfig.Builder;
  15. import org.apache.http.client.entity.UrlEncodedFormEntity;
  16. import org.apache.http.client.methods.HttpGet;
  17. import org.apache.http.client.methods.HttpPost;
  18. import org.apache.http.conn.ConnectTimeoutException;
  19. import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
  20. import org.apache.http.conn.ssl.SSLContextBuilder;
  21. import org.apache.http.conn.ssl.TrustStrategy;
  22. import org.apache.http.conn.ssl.X509HostnameVerifier;
  23. import org.apache.http.entity.ContentType;
  24. import org.apache.http.entity.StringEntity;
  25. import org.apache.http.impl.client.CloseableHttpClient;
  26. import org.apache.http.impl.client.HttpClients;
  27. import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
  28. import org.apache.http.message.BasicNameValuePair;
  29. import java.io.IOException;
  30. import java.net.SocketTimeoutException;
  31. import java.security.GeneralSecurityException;
  32. import java.security.cert.CertificateException;
  33. import java.security.cert.X509Certificate;
  34. import java.util.ArrayList;
  35. import java.util.List;
  36. import java.util.Map;
  37. import java.util.Set;
  38. public class HttpClientUtils {
  39. public static final int connTimeout=10000;
  40. public static final int readTimeout=10000;
  41. public static final String charset="UTF-8";
  42. private static HttpClient client = null;
  43. static {
  44. PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
  45. cm.setMaxTotal(128);
  46. cm.setDefaultMaxPerRoute(128);
  47. client = HttpClients.custom().setConnectionManager(cm).build();
  48. }
  49. public static String postParameters(String url, String parameterStr) throws ConnectTimeoutException, SocketTimeoutException, Exception{
  50. return post(url,parameterStr,"application/x-www-form-urlencoded",charset,connTimeout,readTimeout);
  51. }
  52. public static String postParameters(String url, String parameterStr,String charset, Integer connTimeout, Integer readTimeout) throws ConnectTimeoutException, SocketTimeoutException, Exception{
  53. return post(url,parameterStr,"application/x-www-form-urlencoded",charset,connTimeout,readTimeout);
  54. }
  55. public static String postParameters(String url, Map<String, String> params) throws ConnectTimeoutException,
  56. SocketTimeoutException, Exception {
  57. return postForm(url, params, null, connTimeout, readTimeout);
  58. }
  59. public static String postParameters(String url, Map<String, String> params, Integer connTimeout,Integer readTimeout) throws ConnectTimeoutException,
  60. SocketTimeoutException, Exception {
  61. return postForm(url, params, null, connTimeout, readTimeout);
  62. }
  63. public static String get(String url) throws Exception {
  64. return get(url, charset, null, null);
  65. }
  66. public static String get(String url, String charset) throws Exception {
  67. return get(url, charset, connTimeout, readTimeout);
  68. }
  69. /**
  70. * 发送一个 Post 请求, 使用指定的字符集编码.
  71. *
  72. * @param url
  73. * @param body RequestBody
  74. * @param mimeType 例如 application/xml "application/x-www-form-urlencoded" a=1&b=2&c=3
  75. * @param charset 编码
  76. * @param connTimeout 建立链接超时时间,毫秒.
  77. * @param readTimeout 响应超时时间,毫秒.
  78. * @return ResponseBody, 使用指定的字符集编码.
  79. * @throws ConnectTimeoutException 建立链接超时异常
  80. * @throws SocketTimeoutException 响应超时
  81. * @throws Exception
  82. */
  83. public static String post(String url, String body, String mimeType,String charset, Integer connTimeout, Integer readTimeout)
  84. throws ConnectTimeoutException, SocketTimeoutException, Exception {
  85. HttpClient client = null;
  86. HttpPost post = new HttpPost(url);
  87. String result = "";
  88. try {
  89. if (StringUtils.isNotBlank(body)) {
  90. HttpEntity entity = new StringEntity(body, ContentType.create(mimeType, charset));
  91. post.setEntity(entity);
  92. }
  93. // 设置参数
  94. Builder customReqConf = RequestConfig.custom();
  95. if (connTimeout != null) {
  96. customReqConf.setConnectTimeout(connTimeout);
  97. }
  98. if (readTimeout != null) {
  99. customReqConf.setSocketTimeout(readTimeout);
  100. }
  101. post.setConfig(customReqConf.build());
  102. HttpResponse res;
  103. if (url.startsWith("https")) {
  104. // 执行 Https 请求.
  105. client = createSSLInsecureClient();
  106. res = client.execute(post);
  107. } else {
  108. // 执行 Http 请求.
  109. client = HttpClientUtils.client;
  110. res = client.execute(post);
  111. }
  112. result = IOUtils.toString(res.getEntity().getContent(), charset);
  113. } finally {
  114. post.releaseConnection();
  115. if (url.startsWith("https") && client != null&& client instanceof CloseableHttpClient) {
  116. ((CloseableHttpClient) client).close();
  117. }
  118. }
  119. return result;
  120. }
  121. /**
  122. * 提交form表单
  123. *
  124. * @param url
  125. * @param params
  126. * @param connTimeout
  127. * @param readTimeout
  128. * @return
  129. * @throws ConnectTimeoutException
  130. * @throws SocketTimeoutException
  131. * @throws Exception
  132. */
  133. public static String postForm(String url, Map<String, String> params, Map<String, String> headers, Integer connTimeout,Integer readTimeout) throws ConnectTimeoutException,
  134. SocketTimeoutException, Exception {
  135. HttpClient client = null;
  136. HttpPost post = new HttpPost(url);
  137. try {
  138. if (params != null && !params.isEmpty()) {
  139. List<NameValuePair> formParams = new ArrayList<NameValuePair>();
  140. Set<Map.Entry<String, String>> entrySet = params.entrySet();
  141. for (Map.Entry<String, String> entry : entrySet) {
  142. formParams.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
  143. }
  144. UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formParams, Consts.UTF_8);
  145. post.setEntity(entity);
  146. }
  147. if (headers != null && !headers.isEmpty()) {
  148. for (Map.Entry<String, String> entry : headers.entrySet()) {
  149. post.addHeader(entry.getKey(), entry.getValue());
  150. }
  151. }
  152. // 设置参数
  153. Builder customReqConf = RequestConfig.custom();
  154. if (connTimeout != null) {
  155. customReqConf.setConnectTimeout(connTimeout);
  156. }
  157. if (readTimeout != null) {
  158. customReqConf.setSocketTimeout(readTimeout);
  159. }
  160. post.setConfig(customReqConf.build());
  161. HttpResponse res = null;
  162. if (url.startsWith("https")) {
  163. // 执行 Https 请求.
  164. client = createSSLInsecureClient();
  165. res = client.execute(post);
  166. } else {
  167. // 执行 Http 请求.
  168. client = HttpClientUtils.client;
  169. res = client.execute(post);
  170. }
  171. return IOUtils.toString(res.getEntity().getContent(), "UTF-8");
  172. } finally {
  173. post.releaseConnection();
  174. if (url.startsWith("https") && client != null
  175. && client instanceof CloseableHttpClient) {
  176. ((CloseableHttpClient) client).close();
  177. }
  178. }
  179. }
  180. /**
  181. * 发送一个 GET 请求
  182. *
  183. * @param url
  184. * @param charset
  185. * @param connTimeout 建立链接超时时间,毫秒.
  186. * @param readTimeout 响应超时时间,毫秒.
  187. * @return
  188. * @throws ConnectTimeoutException 建立链接超时
  189. * @throws SocketTimeoutException 响应超时
  190. * @throws Exception
  191. */
  192. public static String get(String url, String charset, Integer connTimeout,Integer readTimeout)
  193. throws ConnectTimeoutException,SocketTimeoutException, Exception {
  194. HttpClient client = null;
  195. HttpGet get = new HttpGet(url);
  196. String result = "";
  197. try {
  198. // 设置参数
  199. Builder customReqConf = RequestConfig.custom();
  200. if (connTimeout != null) {
  201. customReqConf.setConnectTimeout(connTimeout);
  202. }
  203. if (readTimeout != null) {
  204. customReqConf.setSocketTimeout(readTimeout);
  205. }
  206. get.setConfig(customReqConf.build());
  207. HttpResponse res = null;
  208. if (url.startsWith("https")) {
  209. // 执行 Https 请求.
  210. client = createSSLInsecureClient();
  211. res = client.execute(get);
  212. } else {
  213. // 执行 Http 请求.
  214. client = HttpClientUtils.client;
  215. res = client.execute(get);
  216. }
  217. result = IOUtils.toString(res.getEntity().getContent(), charset);
  218. } finally {
  219. get.releaseConnection();
  220. if (url.startsWith("https") && client != null && client instanceof CloseableHttpClient) {
  221. ((CloseableHttpClient) client).close();
  222. }
  223. }
  224. return result;
  225. }
  226. /**
  227. * 从 response 里获取 charset
  228. *
  229. * @param ressponse
  230. * @return
  231. */
  232. @SuppressWarnings("unused")
  233. private static String getCharsetFromResponse(HttpResponse ressponse) {
  234. // Content-Type:text/html; charset=GBK
  235. if (ressponse.getEntity() != null && ressponse.getEntity().getContentType() != null && ressponse.getEntity().getContentType().getValue() != null) {
  236. String contentType = ressponse.getEntity().getContentType().getValue();
  237. if (contentType.contains("charset=")) {
  238. return contentType.substring(contentType.indexOf("charset=") + 8);
  239. }
  240. }
  241. return null;
  242. }
  243. /**
  244. * 创建 SSL连接
  245. * @return
  246. * @throws GeneralSecurityException
  247. */
  248. private static CloseableHttpClient createSSLInsecureClient() throws GeneralSecurityException {
  249. try {
  250. SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
  251. public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
  252. return true;
  253. }
  254. }).build();
  255. SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, new X509HostnameVerifier() {
  256. @Override
  257. public boolean verify(String arg0, SSLSession arg1) {
  258. return true;
  259. }
  260. @Override
  261. public void verify(String host, SSLSocket ssl)
  262. throws IOException {
  263. }
  264. @Override
  265. public void verify(String host, X509Certificate cert)
  266. throws SSLException {
  267. }
  268. @Override
  269. public void verify(String host, String[] cns,
  270. String[] subjectAlts) throws SSLException {
  271. }
  272. });
  273. return HttpClients.custom().setSSLSocketFactory(sslsf).build();
  274. } catch (GeneralSecurityException e) {
  275. throw e;
  276. }
  277. }
  278. }