HttpUtils.java 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366
  1. package com.ygj.yuemum.utils;
  2. import org.apache.commons.lang.StringUtils;
  3. import org.apache.http.HttpResponse;
  4. import org.apache.http.NameValuePair;
  5. import org.apache.http.client.HttpClient;
  6. import org.apache.http.client.config.AuthSchemes;
  7. import org.apache.http.client.config.CookieSpecs;
  8. import org.apache.http.client.config.RequestConfig;
  9. import org.apache.http.client.entity.UrlEncodedFormEntity;
  10. import org.apache.http.client.methods.HttpDelete;
  11. import org.apache.http.client.methods.HttpGet;
  12. import org.apache.http.client.methods.HttpPost;
  13. import org.apache.http.client.methods.HttpPut;
  14. import org.apache.http.config.Registry;
  15. import org.apache.http.config.RegistryBuilder;
  16. import org.apache.http.conn.socket.ConnectionSocketFactory;
  17. import org.apache.http.conn.socket.PlainConnectionSocketFactory;
  18. import org.apache.http.conn.ssl.NoopHostnameVerifier;
  19. import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
  20. import org.apache.http.entity.ByteArrayEntity;
  21. import org.apache.http.entity.StringEntity;
  22. import org.apache.http.impl.client.CloseableHttpClient;
  23. import org.apache.http.impl.client.HttpClients;
  24. import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
  25. import org.apache.http.message.BasicNameValuePair;
  26. import javax.net.ssl.SSLContext;
  27. import javax.net.ssl.TrustManager;
  28. import javax.net.ssl.X509TrustManager;
  29. import java.io.UnsupportedEncodingException;
  30. import java.net.URLEncoder;
  31. import java.security.KeyManagementException;
  32. import java.security.NoSuchAlgorithmException;
  33. import java.security.cert.X509Certificate;
  34. import java.util.ArrayList;
  35. import java.util.Arrays;
  36. import java.util.List;
  37. import java.util.Map;
  38. /**
  39. * @program:
  40. * @description:
  41. * @author:
  42. * @create: 2019-11-06 16:48
  43. **/
  44. public class HttpUtils {
  45. private static int defaultConnectTimeout = 60000;
  46. private static int defaultConnectionRequestTimeout = 60000;
  47. private static int defaultSocketTimeout = 60000;
  48. /**
  49. * 获取 HttpClient
  50. *
  51. * @param host
  52. * @param path
  53. * @return
  54. */
  55. public static HttpClient wrapClient(String host, String path) {
  56. // HttpClient httpClient = HttpClientBuilder.create().build();
  57. CloseableHttpClient httpClient = HttpClients.custom().build();
  58. if (host != null && host.startsWith("https://")) {
  59. return sslClient();
  60. } else if (StringUtils.isBlank(host) && path != null && path.startsWith("https://")) {
  61. return sslClient();
  62. }
  63. return httpClient;
  64. }
  65. /**
  66. * 在调用SSL之前需要重写验证方法,取消检测SSL
  67. * 创建ConnectionManager,添加Connection配置信息
  68. *
  69. * @return HttpClient 支持https
  70. */
  71. public static HttpClient sslClient() {
  72. try {
  73. // 在调用SSL之前需要重写验证方法,取消检测SSL
  74. X509TrustManager trustManager = new X509TrustManager() {
  75. @Override
  76. public X509Certificate[] getAcceptedIssuers() {
  77. return null;
  78. }
  79. @Override
  80. public void checkClientTrusted(X509Certificate[] xcs, String str) {
  81. }
  82. @Override
  83. public void checkServerTrusted(X509Certificate[] xcs, String str) {
  84. }
  85. };
  86. SSLContext ctx = SSLContext.getInstance(SSLConnectionSocketFactory.TLS);
  87. ctx.init(null, new TrustManager[]{trustManager}, null);
  88. SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(ctx, NoopHostnameVerifier.INSTANCE);
  89. // 创建Registry
  90. RequestConfig requestConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD_STRICT)
  91. .setExpectContinueEnabled(Boolean.TRUE).setTargetPreferredAuthSchemes(Arrays.asList(AuthSchemes.NTLM, AuthSchemes.DIGEST))
  92. .setProxyPreferredAuthSchemes(Arrays.asList(AuthSchemes.BASIC)).setConnectTimeout(2000).build();
  93. Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
  94. .register("http", PlainConnectionSocketFactory.INSTANCE)
  95. .register("https", socketFactory).build();
  96. // 创建ConnectionManager,添加Connection配置信息
  97. PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
  98. connectionManager.setDefaultMaxPerRoute(20);
  99. connectionManager.setMaxTotal(200);
  100. CloseableHttpClient closeableHttpClient = HttpClients.custom()
  101. .setConnectionManager(connectionManager)
  102. .setDefaultRequestConfig(requestConfig).build();
  103. return closeableHttpClient;
  104. } catch (KeyManagementException ex) {
  105. throw new RuntimeException(ex);
  106. } catch (NoSuchAlgorithmException ex) {
  107. throw new RuntimeException(ex);
  108. }
  109. }
  110. /**
  111. * get
  112. *
  113. * @param host
  114. * @param path
  115. * @param headers
  116. * @param querys
  117. * @return
  118. * @throws Exception
  119. */
  120. public static HttpResponse doGet(String host, String path,
  121. Map<String, String> headers,
  122. Map<String, String> querys)
  123. throws Exception {
  124. HttpClient httpClient = wrapClient(host, path);
  125. HttpGet request = new HttpGet(buildUrl(host, path, querys));
  126. for (Map.Entry<String, String> e : headers.entrySet()) {
  127. request.addHeader(e.getKey(), e.getValue());
  128. }
  129. return httpClient.execute(request);
  130. }
  131. /**
  132. * post form
  133. *
  134. * @param host
  135. * @param path
  136. * @param headers
  137. * @param querys
  138. * @param bodys
  139. * @return
  140. * @throws Exception
  141. */
  142. public static HttpResponse doPost(String host, String path,
  143. Map<String, String> headers,
  144. Map<String, String> querys,
  145. Map<String, String> bodys)
  146. throws Exception {
  147. HttpClient httpClient = wrapClient(host, path);
  148. HttpPost request = new HttpPost(buildUrl(host, path, querys));
  149. for (Map.Entry<String, String> e : headers.entrySet()) {
  150. request.addHeader(e.getKey(), e.getValue());
  151. }
  152. if (bodys != null) {
  153. List<NameValuePair> nameValuePairList = new ArrayList<NameValuePair>();
  154. for (String key : bodys.keySet()) {
  155. nameValuePairList.add(new BasicNameValuePair(key, bodys.get(key)));
  156. }
  157. UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(nameValuePairList, "utf-8");
  158. formEntity.setContentType("application/x-www-form-urlencoded; charset=UTF-8");
  159. request.setEntity(formEntity);
  160. }
  161. return httpClient.execute(request);
  162. }
  163. /**
  164. * Post String
  165. *
  166. * @param host
  167. * @param path
  168. * @param headers
  169. * @param querys
  170. * @param body
  171. * @return
  172. * @throws Exception
  173. */
  174. public static HttpResponse doPost(String host, String path,
  175. Map<String, String> headers,
  176. Map<String, String> querys,
  177. String body)
  178. throws Exception {
  179. HttpClient httpClient = wrapClient(host, path);
  180. HttpPost request = new HttpPost(buildUrl(host, path, querys));
  181. for (Map.Entry<String, String> e : headers.entrySet()) {
  182. request.addHeader(e.getKey(), e.getValue());
  183. }
  184. if (StringUtils.isNotBlank(body)) {
  185. request.setEntity(new StringEntity(body, "utf-8"));
  186. }
  187. request.setConfig(getRequestConfig(defaultConnectTimeout, defaultConnectionRequestTimeout, defaultSocketTimeout));
  188. return httpClient.execute(request);
  189. }
  190. /**
  191. * Post stream
  192. *
  193. * @param host
  194. * @param path
  195. * @param headers
  196. * @param querys
  197. * @param body
  198. * @return
  199. * @throws Exception
  200. */
  201. public static HttpResponse doPost(String host, String path,
  202. Map<String, String> headers,
  203. Map<String, String> querys,
  204. byte[] body)
  205. throws Exception {
  206. HttpClient httpClient = wrapClient(host, path);
  207. HttpPost request = new HttpPost(buildUrl(host, path, querys));
  208. for (Map.Entry<String, String> e : headers.entrySet()) {
  209. request.addHeader(e.getKey(), e.getValue());
  210. }
  211. if (body != null) {
  212. request.setEntity(new ByteArrayEntity(body));
  213. }
  214. return httpClient.execute(request);
  215. }
  216. /**
  217. * Put String
  218. *
  219. * @param host
  220. * @param path
  221. * @param headers
  222. * @param querys
  223. * @param body
  224. * @return
  225. * @throws Exception
  226. */
  227. public static HttpResponse doPut(String host, String path,
  228. Map<String, String> headers,
  229. Map<String, String> querys,
  230. String body)
  231. throws Exception {
  232. HttpClient httpClient = wrapClient(host, path);
  233. HttpPut request = new HttpPut(buildUrl(host, path, querys));
  234. for (Map.Entry<String, String> e : headers.entrySet()) {
  235. request.addHeader(e.getKey(), e.getValue());
  236. }
  237. if (StringUtils.isNotBlank(body)) {
  238. request.setEntity(new StringEntity(body, "utf-8"));
  239. }
  240. return httpClient.execute(request);
  241. }
  242. /**
  243. * Put stream
  244. *
  245. * @param host
  246. * @param path
  247. * @param headers
  248. * @param querys
  249. * @param body
  250. * @return
  251. * @throws Exception
  252. */
  253. public static HttpResponse doPut(String host, String path,
  254. Map<String, String> headers,
  255. Map<String, String> querys,
  256. byte[] body)
  257. throws Exception {
  258. HttpClient httpClient = wrapClient(host, path);
  259. HttpPut request = new HttpPut(buildUrl(host, path, querys));
  260. for (Map.Entry<String, String> e : headers.entrySet()) {
  261. request.addHeader(e.getKey(), e.getValue());
  262. }
  263. if (body != null) {
  264. request.setEntity(new ByteArrayEntity(body));
  265. }
  266. return httpClient.execute(request);
  267. }
  268. /**
  269. * Delete
  270. *
  271. * @param host
  272. * @param path
  273. * @param headers
  274. * @param querys
  275. * @return
  276. * @throws Exception
  277. */
  278. public static HttpResponse doDelete(String host, String path,
  279. Map<String, String> headers,
  280. Map<String, String> querys)
  281. throws Exception {
  282. HttpClient httpClient = wrapClient(host, path);
  283. HttpDelete request = new HttpDelete(buildUrl(host, path, querys));
  284. for (Map.Entry<String, String> e : headers.entrySet()) {
  285. request.addHeader(e.getKey(), e.getValue());
  286. }
  287. return httpClient.execute(request);
  288. }
  289. /**
  290. * 构建请求的 url
  291. *
  292. * @param host
  293. * @param path
  294. * @param querys
  295. * @return
  296. * @throws UnsupportedEncodingException
  297. */
  298. private static String buildUrl(String host, String path, Map<String, String> querys) throws UnsupportedEncodingException {
  299. StringBuilder sbUrl = new StringBuilder();
  300. if (!StringUtils.isBlank(host)) {
  301. sbUrl.append(host);
  302. }
  303. if (!StringUtils.isBlank(path)) {
  304. sbUrl.append(path);
  305. }
  306. if (null != querys) {
  307. StringBuilder sbQuery = new StringBuilder();
  308. for (Map.Entry<String, String> query : querys.entrySet()) {
  309. if (0 < sbQuery.length()) {
  310. sbQuery.append("&");
  311. }
  312. if (StringUtils.isBlank(query.getKey()) && !StringUtils.isBlank(query.getValue())) {
  313. sbQuery.append(query.getValue());
  314. }
  315. if (!StringUtils.isBlank(query.getKey())) {
  316. sbQuery.append(query.getKey());
  317. if (!StringUtils.isBlank(query.getValue())) {
  318. sbQuery.append("=");
  319. sbQuery.append(URLEncoder.encode(query.getValue(), "utf-8"));
  320. }
  321. }
  322. }
  323. if (0 < sbQuery.length()) {
  324. sbUrl.append("?").append(sbQuery);
  325. }
  326. }
  327. return sbUrl.toString();
  328. }
  329. /**
  330. * 单位毫秒
  331. * @return
  332. */
  333. private static RequestConfig getRequestConfig(int connectTimeout, int connectionRequestTimeout, int socketTimeout){
  334. RequestConfig requestConfig = RequestConfig.custom()
  335. .setConnectTimeout(connectTimeout).setConnectionRequestTimeout(connectionRequestTimeout)
  336. .setSocketTimeout(socketTimeout).build();
  337. return requestConfig;
  338. }
  339. }