HttpUtil.java 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428
  1. package api.common.util;
  2. import lombok.extern.slf4j.Slf4j;
  3. import org.apache.http.HttpEntity;
  4. import org.apache.http.HttpResponse;
  5. import org.apache.http.client.config.RequestConfig;
  6. import org.apache.http.client.methods.CloseableHttpResponse;
  7. import org.apache.http.client.methods.HttpGet;
  8. import org.apache.http.client.methods.HttpPost;
  9. import org.apache.http.conn.ssl.NoopHostnameVerifier;
  10. import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
  11. import org.apache.http.entity.ContentType;
  12. import org.apache.http.entity.StringEntity;
  13. import org.apache.http.entity.mime.HttpMultipartMode;
  14. import org.apache.http.entity.mime.MultipartEntityBuilder;
  15. import org.apache.http.entity.mime.content.FileBody;
  16. import org.apache.http.impl.client.CloseableHttpClient;
  17. import org.apache.http.impl.client.HttpClients;
  18. import org.apache.http.util.EntityUtils;
  19. import javax.net.ssl.SSLContext;
  20. import javax.net.ssl.TrustManager;
  21. import javax.net.ssl.X509TrustManager;
  22. import java.io.File;
  23. import java.io.IOException;
  24. import java.io.InputStream;
  25. import java.nio.charset.StandardCharsets;
  26. import java.security.cert.X509Certificate;
  27. import java.util.Map;
  28. /**
  29. * <dependency>
  30. * <groupId>org.apache.httpcomponents</groupId>
  31. * <artifactId>httpclient</artifactId>
  32. * <version>${http.client.version}</version>
  33. * </dependency>
  34. */
  35. @Slf4j
  36. public class HttpUtil {
  37. // public static CloseableHttpClient getHttpClient() throws NoSuchAlgorithmException, KeyStoreException, KeyManagementException {
  38. //
  39. // PlainConnectionSocketFactory plainConnectionSocketFactory = new PlainConnectionSocketFactory();
  40. // SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(
  41. // SSLContextBuilder.create().loadTrustMaterial(null, (x509Certificates, s) -> true).build(), // 全部信任 不做身份鉴定
  42. // new String[]{"SSLv2Hello", "SSLv3", "TLSv1", "TLSv1.2"},
  43. // null,
  44. // NoopHostnameVerifier.INSTANCE);
  45. // Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
  46. // .register("http", plainConnectionSocketFactory)
  47. // .register("https", sslConnectionSocketFactory)
  48. // .build();
  49. // PoolingHttpClientConnectionManager pool = new PoolingHttpClientConnectionManager(registry);
  50. // pool.setMaxTotal(300);
  51. // pool.setDefaultMaxPerRoute(300);
  52. // return HttpClients.custom().setConnectionManager(pool).build();
  53. // }
  54. public static CloseableHttpClient getHttpClient() {
  55. return getCloseableHttpClient();
  56. }
  57. private static CloseableHttpClient getCloseableHttpClient() {
  58. try {
  59. SSLContext sslContext = SSLContext.getInstance("TLS");
  60. X509TrustManager x509TrustManager = new X509TrustManager() {
  61. @Override
  62. public X509Certificate[] getAcceptedIssuers() {
  63. return null;
  64. }
  65. @Override
  66. public void checkClientTrusted(X509Certificate[] arg0, String arg1) {
  67. }
  68. @Override
  69. public void checkServerTrusted(X509Certificate[] arg0, String arg1) {
  70. }
  71. };
  72. sslContext.init(null, new TrustManager[]{x509TrustManager}, null);
  73. SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE);
  74. // PoolingHttpClientConnectionManager pool = new PoolingHttpClientConnectionManager();
  75. // pool.setMaxTotal(300);
  76. // pool.setDefaultMaxPerRoute(300);
  77. // return HttpClients.custom().setConnectionManager(pool).setSSLSocketFactory(sslConnectionSocketFactory).build();
  78. return HttpClients.custom().setSSLSocketFactory(sslConnectionSocketFactory).build();
  79. } catch (Exception exception) {
  80. throw new RuntimeException("获取 httpClient 失败。", exception);
  81. }
  82. }
  83. public static RequestConfig getRequestConfig() {
  84. return RequestConfig.custom()
  85. .setSocketTimeout(5000)
  86. .setConnectTimeout(5000)
  87. .setConnectionRequestTimeout(5000)
  88. .setRedirectsEnabled(false)
  89. .setExpectContinueEnabled(false)
  90. .build();
  91. }
  92. /**
  93. * 发送本地文件
  94. *
  95. * @param url http请求路径
  96. * @param file 文件对象
  97. * @return 响应体
  98. */
  99. public static String post(String url, File file) {
  100. String result = null;
  101. try {
  102. CloseableHttpClient client = getCloseableHttpClient();
  103. RequestConfig config = getRequestConfig();
  104. //1 创建 post 请求
  105. HttpPost post = new HttpPost(url);
  106. post.setConfig(config);
  107. //2 设置请求体
  108. post.setEntity(MultipartEntityBuilder.create().setCharset(StandardCharsets.UTF_8).setMode(HttpMultipartMode.BROWSER_COMPATIBLE) //设置浏览器兼容模式
  109. .addPart("file", new FileBody(file, ContentType.MULTIPART_FORM_DATA)).build());
  110. //3 获取响应结果
  111. HttpResponse response = client.execute(post);
  112. HttpEntity responseEntity = response.getEntity();
  113. result = EntityUtils.toString(responseEntity);
  114. //4 关闭流
  115. EntityUtils.consume(responseEntity);
  116. return result;
  117. } catch (org.apache.http.conn.ConnectTimeoutException cte) {
  118. log.debug(url + " 请求超时。", cte);
  119. log.info(url + " 请求超时。");
  120. } catch (Exception e) {
  121. log.info("请求 " + url + " 失败。", e);
  122. }
  123. return result;
  124. }
  125. /**
  126. * 默认请求头的 get 请求,参数拼接到 url 上
  127. *
  128. * @param url 请求路径带参数
  129. * @return 请求结果
  130. */
  131. public static String get(String url) {
  132. String result;
  133. try {
  134. //1 创建 GET 对象
  135. HttpGet get = new HttpGet(url);
  136. get.setConfig(getRequestConfig());
  137. //2 执行获取请求结果
  138. result = EntityUtils.toString(getCloseableHttpClient().execute(get).getEntity());
  139. } catch (IOException e) {
  140. throw new RuntimeException(e);
  141. }
  142. return result;
  143. }
  144. /**
  145. * 默认请求头的 get 请求
  146. *
  147. * @param closeableHttpClient http 客户端
  148. * @param requestConfig 请求配置
  149. * @param url 请求路径带参数
  150. * @return 请求结果
  151. */
  152. public static String get(CloseableHttpClient closeableHttpClient, RequestConfig requestConfig, String url) {
  153. log.info("发送HTTP请求:" + url);
  154. String result = null;
  155. try {
  156. //1 创建 post 请求
  157. HttpGet get = new HttpGet(url);
  158. get.setConfig(requestConfig);
  159. //2 发送请求
  160. CloseableHttpResponse response = closeableHttpClient.execute(get);
  161. //3 处理返回结果,如果状态码为200,就是正常返回
  162. int statusCode = response.getStatusLine().getStatusCode();
  163. if (statusCode == 200) {
  164. result = EntityUtils.toString(response.getEntity());
  165. } else {
  166. log.error(response.getEntity().toString());
  167. throw new RuntimeException("请求错误:" + response);
  168. }
  169. } catch (org.apache.http.conn.ConnectTimeoutException cte) {
  170. log.debug(url + " 请求超时。", cte);
  171. log.info(url + " 请求超时。");
  172. } catch (Exception e) {
  173. log.info("请求 " + url + " 失败。", e);
  174. }
  175. return result;
  176. }
  177. /**
  178. * 带请求头的 get 请求
  179. *
  180. * @param closeableHttpClient http 客户端
  181. * @param requestConfig 请求配置
  182. * @param url 请求路径带参数
  183. * @param headers 请求头
  184. * @return 请求结果
  185. * @throws IOException IO异常
  186. */
  187. public static String get(CloseableHttpClient closeableHttpClient, RequestConfig requestConfig, String url,
  188. Map<String, String> headers) throws IOException {
  189. //1 创建 post 请求
  190. HttpGet get = new HttpGet(url);
  191. //2 设置请求默认配置
  192. get.setConfig(requestConfig);
  193. //3 设置请求头 post.setHeader("Content-type", "application/json; charset=utf-8");
  194. if (!CollectionUtil.isEmpty(headers)) {
  195. headers.forEach(get::setHeader);
  196. }
  197. //4 发送请求
  198. CloseableHttpResponse response = closeableHttpClient.execute(get);
  199. //5 处理返回结果,
  200. //5-1 如果状态码为200,就是正常返回
  201. int statusCode = response.getStatusLine().getStatusCode();
  202. if (statusCode == 200) {
  203. return EntityUtils.toString(response.getEntity());
  204. } else {
  205. throw new RuntimeException("------- 请求错误:" + statusCode);
  206. }
  207. }
  208. /**
  209. * 默认请求头的 get 请求下载文件
  210. *
  211. * @param url 请求地址
  212. * @return 文件流
  213. */
  214. public static InputStream getInputStream(String url) {
  215. try {
  216. log.info("发送请求:" + url);
  217. CloseableHttpClient closeableHttpClient = getCloseableHttpClient();
  218. RequestConfig requestConfig = getRequestConfig();
  219. return getInputStream(closeableHttpClient, requestConfig, url, null);
  220. } catch (IOException e) {
  221. throw new RuntimeException(e);
  222. }
  223. }
  224. /**
  225. * 默认请求头的 get 请求下载文件
  226. *
  227. * @param url 请求地址
  228. * @return 文件流
  229. * @throws IOException 异常
  230. */
  231. public static InputStream getInputStream(CloseableHttpClient closeableHttpClient, RequestConfig requestConfig, String url) throws IOException {
  232. return getInputStream(closeableHttpClient, requestConfig, url, null);
  233. }
  234. /**
  235. * 自定义请求头的 get 请求下载文件
  236. *
  237. * @param url 请求地址
  238. * @param headers 请求头,可为 null
  239. * @return 文件流
  240. * @throws IOException 异常
  241. */
  242. public static InputStream getInputStream(CloseableHttpClient closeableHttpClient, RequestConfig requestConfig, String url, Map<String, String> headers) throws IOException {
  243. InputStream result = null;
  244. try {
  245. //1 创建 post 请求
  246. HttpGet get = new HttpGet(url);
  247. //2 设置请求默认配置
  248. get.setConfig(requestConfig);
  249. //3 设置请求头 post.setHeader("Content-type", "application/json; charset=utf-8");
  250. if (!CollectionUtil.isEmpty(headers)) {
  251. headers.forEach(get::setHeader);
  252. }
  253. //4 发送请求
  254. CloseableHttpResponse response = closeableHttpClient.execute(get);
  255. //5 处理返回结果,
  256. //5-1 如果状态码为200,就是正常返回
  257. int statusCode = response.getStatusLine().getStatusCode();
  258. log.info("请求 " + url + " 状态码为:" + statusCode);
  259. if (statusCode == 200) {
  260. result = response.getEntity().getContent();
  261. }
  262. } catch (Exception e) {
  263. log.info("请求 " + url + " 失败。", e);
  264. }
  265. return result;
  266. }
  267. /**
  268. * 自定义请求头的 post 请求
  269. */
  270. public static String post(String url, Map<String, String> headers, Map<String, String> params) throws IOException {
  271. CloseableHttpClient closeableHttpClient = getCloseableHttpClient();
  272. RequestConfig requestConfig = getRequestConfig();
  273. //1 创建 post 请求
  274. HttpPost post = new HttpPost(url);
  275. //2 设置请求默认配置
  276. post.setConfig(requestConfig);
  277. //3 设置请求头 post.setHeader("Content-type", "application/json; charset=utf-8");
  278. if (!CollectionUtil.isEmpty(headers)) {
  279. headers.forEach(post::setHeader);
  280. }
  281. //4 设置请求体
  282. post.addHeader("Content-Type", "application/json");
  283. if (!CollectionUtil.isEmpty(params)) {
  284. post.setEntity(new StringEntity(JsonUtil.beanToJson(params), "utf-8"));
  285. }
  286. //5 发送请求
  287. CloseableHttpResponse response = closeableHttpClient.execute(post);
  288. //6 处理返回结果,
  289. //6-1 如果状态码为200,就是正常返回
  290. int statusCode = response.getStatusLine().getStatusCode();
  291. if (statusCode == 200) {
  292. return EntityUtils.toString(response.getEntity());
  293. } else {
  294. throw new RuntimeException("请求错误:" + statusCode);
  295. }
  296. }
  297. /**
  298. * 自定义请求头的 post 请求
  299. */
  300. public static String post(CloseableHttpClient closeableHttpClient, RequestConfig requestConfig, String url, Map<String, String> headers, Map<String, String> params) throws IOException {
  301. //1 创建 post 请求
  302. HttpPost post = new HttpPost(url);
  303. //2 设置请求默认配置
  304. post.setConfig(requestConfig);
  305. //3 设置请求头 post.setHeader("Content-type", "application/json; charset=utf-8");
  306. if (!CollectionUtil.isEmpty(headers)) {
  307. headers.forEach(post::setHeader);
  308. }
  309. //4 设置请求体
  310. post.addHeader("Content-Type", "application/json");
  311. if (!CollectionUtil.isEmpty(params)) {
  312. post.setEntity(new StringEntity(JsonUtil.beanToJson(params), "utf-8"));
  313. }
  314. //5 发送请求
  315. CloseableHttpResponse response = closeableHttpClient.execute(post);
  316. //6 处理返回结果,
  317. //6-1 如果状态码为200,就是正常返回
  318. int statusCode = response.getStatusLine().getStatusCode();
  319. if (statusCode == 200) {
  320. return EntityUtils.toString(response.getEntity());
  321. } else {
  322. throw new RuntimeException("请求错误:" + statusCode);
  323. }
  324. }
  325. //
  326. // /**
  327. // * 通过 get 请求下载文件
  328. // * 发送 get 请求,get 请求的参数在 url 里
  329. // *
  330. // * @param url 请求地址
  331. // * @param headers 请求头,可为 null
  332. // * @return 文件流
  333. // * @throws IOException 异常
  334. // */
  335. // public static InputStream getDownload(String url, Map<String, String> headers) throws IOException {
  336. // //1 创建 post 请求
  337. // HttpGet get = new HttpGet(url);
  338. // //2 设置请求默认配置
  339. // get.setConfig(requestConfig);
  340. // //3 设置请求头 post.setHeader("Content-type", "application/json; charset=utf-8");
  341. // if (!CollectionUtil.isEmpty(headers)) {
  342. // headers.forEach(get::setHeader);
  343. // }
  344. // //4 发送请求
  345. // CloseableHttpResponse response = httpClient.execute(get);
  346. // //5 处理返回结果,
  347. // //5-1 如果状态码为200,就是正常返回
  348. // int statusCode = response.getStatusLine().getStatusCode();
  349. // if (statusCode == 200) {
  350. // return response.getEntity().getContent();
  351. // } else {
  352. // throw new RuntimeException("------- 请求错误:" + statusCode);
  353. // }
  354. // }
  355. //
  356. //
  357. // /**
  358. // * 发送 post 请求
  359. // */
  360. // public static InputStream postUpload(String url) throws IOException {
  361. // //1 创建 post 请求
  362. // HttpPost post = new HttpPost(url);
  363. // //2 设置请求默认配置
  364. // post.setConfig(requestConfig);
  365. // //3 设置请求头 post.setHeader("Content-type", "application/json; charset=utf-8");
  366. // post.setHeader("Content-type", "multipart/form-data");
  367. // //5 发送请求
  368. // CloseableHttpResponse response = httpClient.execute(post);
  369. // //6 处理返回结果,
  370. // //6-1 如果状态码为 200,就是正常返回
  371. // int statusCode = response.getStatusLine().getStatusCode();
  372. // if (statusCode == 200) {
  373. // return response.getEntity().getContent();
  374. // } else {
  375. // throw new RuntimeException("------- 请求错误:" + statusCode);
  376. // }
  377. // }
  378. //
  379. // /**
  380. // * 发送 post 请求
  381. // */
  382. // public static InputStream postDownload(String url, Map<String, String> headers, Map<String, String> params) throws IOException {
  383. // //1 创建 post 请求
  384. // HttpPost post = new HttpPost(url);
  385. // //2 设置请求默认配置
  386. // post.setConfig(requestConfig);
  387. // //3 设置请求头 post.setHeader("Content-type", "application/json; charset=utf-8");
  388. // if (!CollectionUtil.isEmpty(headers)) {
  389. // headers.forEach(post::setHeader);
  390. // }
  391. // //4 设置请求体
  392. // if (!CollectionUtil.isEmpty(params)) {
  393. // params.forEach(post::setHeader);
  394. // }
  395. // //5 发送请求
  396. // CloseableHttpResponse response = httpClient.execute(post);
  397. // //6 处理返回结果,
  398. // //6-1 如果状态码为 200,就是正常返回
  399. // int statusCode = response.getStatusLine().getStatusCode();
  400. // if (statusCode == 200) {
  401. // return response.getEntity().getContent();
  402. // } else {
  403. // throw new RuntimeException("------- 请求错误:" + statusCode);
  404. // }
  405. // }
  406. }