HttpUtils.java 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368
  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. if (headers != null) {
  182. for (Map.Entry<String, String> e : headers.entrySet()) {
  183. request.addHeader(e.getKey(), e.getValue());
  184. }
  185. }
  186. if (StringUtils.isNotBlank(body)) {
  187. request.setEntity(new StringEntity(body, "utf-8"));
  188. }
  189. request.setConfig(getRequestConfig(defaultConnectTimeout, defaultConnectionRequestTimeout, defaultSocketTimeout));
  190. return httpClient.execute(request);
  191. }
  192. /**
  193. * Post stream
  194. *
  195. * @param host
  196. * @param path
  197. * @param headers
  198. * @param querys
  199. * @param body
  200. * @return
  201. * @throws Exception
  202. */
  203. public static HttpResponse doPost(String host, String path,
  204. Map<String, String> headers,
  205. Map<String, String> querys,
  206. byte[] body)
  207. throws Exception {
  208. HttpClient httpClient = wrapClient(host, path);
  209. HttpPost request = new HttpPost(buildUrl(host, path, querys));
  210. for (Map.Entry<String, String> e : headers.entrySet()) {
  211. request.addHeader(e.getKey(), e.getValue());
  212. }
  213. if (body != null) {
  214. request.setEntity(new ByteArrayEntity(body));
  215. }
  216. return httpClient.execute(request);
  217. }
  218. /**
  219. * Put String
  220. *
  221. * @param host
  222. * @param path
  223. * @param headers
  224. * @param querys
  225. * @param body
  226. * @return
  227. * @throws Exception
  228. */
  229. public static HttpResponse doPut(String host, String path,
  230. Map<String, String> headers,
  231. Map<String, String> querys,
  232. String body)
  233. throws Exception {
  234. HttpClient httpClient = wrapClient(host, path);
  235. HttpPut request = new HttpPut(buildUrl(host, path, querys));
  236. for (Map.Entry<String, String> e : headers.entrySet()) {
  237. request.addHeader(e.getKey(), e.getValue());
  238. }
  239. if (StringUtils.isNotBlank(body)) {
  240. request.setEntity(new StringEntity(body, "utf-8"));
  241. }
  242. return httpClient.execute(request);
  243. }
  244. /**
  245. * Put stream
  246. *
  247. * @param host
  248. * @param path
  249. * @param headers
  250. * @param querys
  251. * @param body
  252. * @return
  253. * @throws Exception
  254. */
  255. public static HttpResponse doPut(String host, String path,
  256. Map<String, String> headers,
  257. Map<String, String> querys,
  258. byte[] body)
  259. throws Exception {
  260. HttpClient httpClient = wrapClient(host, path);
  261. HttpPut request = new HttpPut(buildUrl(host, path, querys));
  262. for (Map.Entry<String, String> e : headers.entrySet()) {
  263. request.addHeader(e.getKey(), e.getValue());
  264. }
  265. if (body != null) {
  266. request.setEntity(new ByteArrayEntity(body));
  267. }
  268. return httpClient.execute(request);
  269. }
  270. /**
  271. * Delete
  272. *
  273. * @param host
  274. * @param path
  275. * @param headers
  276. * @param querys
  277. * @return
  278. * @throws Exception
  279. */
  280. public static HttpResponse doDelete(String host, String path,
  281. Map<String, String> headers,
  282. Map<String, String> querys)
  283. throws Exception {
  284. HttpClient httpClient = wrapClient(host, path);
  285. HttpDelete request = new HttpDelete(buildUrl(host, path, querys));
  286. for (Map.Entry<String, String> e : headers.entrySet()) {
  287. request.addHeader(e.getKey(), e.getValue());
  288. }
  289. return httpClient.execute(request);
  290. }
  291. /**
  292. * 构建请求的 url
  293. *
  294. * @param host
  295. * @param path
  296. * @param querys
  297. * @return
  298. * @throws UnsupportedEncodingException
  299. */
  300. private static String buildUrl(String host, String path, Map<String, String> querys) throws UnsupportedEncodingException {
  301. StringBuilder sbUrl = new StringBuilder();
  302. if (!StringUtils.isBlank(host)) {
  303. sbUrl.append(host);
  304. }
  305. if (!StringUtils.isBlank(path)) {
  306. sbUrl.append(path);
  307. }
  308. if (null != querys) {
  309. StringBuilder sbQuery = new StringBuilder();
  310. for (Map.Entry<String, String> query : querys.entrySet()) {
  311. if (0 < sbQuery.length()) {
  312. sbQuery.append("&");
  313. }
  314. if (StringUtils.isBlank(query.getKey()) && !StringUtils.isBlank(query.getValue())) {
  315. sbQuery.append(query.getValue());
  316. }
  317. if (!StringUtils.isBlank(query.getKey())) {
  318. sbQuery.append(query.getKey());
  319. if (!StringUtils.isBlank(query.getValue())) {
  320. sbQuery.append("=");
  321. sbQuery.append(URLEncoder.encode(query.getValue(), "utf-8"));
  322. }
  323. }
  324. }
  325. if (0 < sbQuery.length()) {
  326. sbUrl.append("?").append(sbQuery);
  327. }
  328. }
  329. return sbUrl.toString();
  330. }
  331. /**
  332. * 单位毫秒
  333. * @return
  334. */
  335. private static RequestConfig getRequestConfig(int connectTimeout, int connectionRequestTimeout, int socketTimeout){
  336. RequestConfig requestConfig = RequestConfig.custom()
  337. .setConnectTimeout(connectTimeout).setConnectionRequestTimeout(connectionRequestTimeout)
  338. .setSocketTimeout(socketTimeout).build();
  339. return requestConfig;
  340. }
  341. }