HttpUtil.java 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431
  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(60000)
  86. .setConnectTimeout(60000)
  87. .setConnectionRequestTimeout(60000)
  88. .build();
  89. }
  90. /**
  91. * 发送本地文件
  92. *
  93. * @param url http请求路径
  94. * @param file 文件对象
  95. * @return 响应体
  96. */
  97. public static String post(String url, File file) {
  98. String result = null;
  99. try {
  100. CloseableHttpClient client = getCloseableHttpClient();
  101. RequestConfig config = getRequestConfig();
  102. //1 创建 post 请求
  103. HttpPost post = new HttpPost(url);
  104. post.setConfig(config);
  105. //2 设置请求体
  106. post.setEntity(MultipartEntityBuilder.create().setCharset(StandardCharsets.UTF_8).setMode(HttpMultipartMode.BROWSER_COMPATIBLE) //设置浏览器兼容模式
  107. .addPart("file", new FileBody(file, ContentType.MULTIPART_FORM_DATA)).build());
  108. //3 获取响应结果
  109. HttpResponse response = client.execute(post);
  110. HttpEntity responseEntity = response.getEntity();
  111. result = EntityUtils.toString(responseEntity);
  112. //4 关闭流
  113. EntityUtils.consume(responseEntity);
  114. return result;
  115. } catch (org.apache.http.conn.ConnectTimeoutException cte) {
  116. log.debug(url + " 请求超时。", cte);
  117. log.info(url + " 请求超时。");
  118. } catch (Exception e) {
  119. log.info("请求 " + url + " 失败。", e);
  120. }
  121. return result;
  122. }
  123. /**
  124. * 默认请求头的 get 请求,参数拼接到 url 上
  125. *
  126. * @param url 请求路径带参数
  127. * @return 请求结果
  128. */
  129. public static String get(String url) {
  130. log.info("发送HTTP请求:" + url);
  131. String result;
  132. try {
  133. //1 创建 GET 对象
  134. HttpGet get = new HttpGet(url);
  135. get.setConfig(getRequestConfig());
  136. //2 执行获取请求结果
  137. result = EntityUtils.toString(getCloseableHttpClient().execute(get).getEntity());
  138. } catch (IOException e) {
  139. throw new RuntimeException(e);
  140. }
  141. return result;
  142. }
  143. /**
  144. * 默认请求头的 get 请求
  145. *
  146. * @param closeableHttpClient http 客户端
  147. * @param requestConfig 请求配置
  148. * @param url 请求路径带参数
  149. * @return 请求结果
  150. */
  151. public static String get(CloseableHttpClient closeableHttpClient, RequestConfig requestConfig, String url) {
  152. log.info("发送HTTP请求:" + url);
  153. String result = null;
  154. try {
  155. //1 创建 post 请求
  156. HttpGet get = new HttpGet(url);
  157. get.setConfig(requestConfig);
  158. //2 发送请求
  159. CloseableHttpResponse response = closeableHttpClient.execute(get);
  160. //3 处理返回结果,如果状态码为200,就是正常返回
  161. int statusCode = response.getStatusLine().getStatusCode();
  162. if (statusCode == 200) {
  163. result = EntityUtils.toString(response.getEntity());
  164. } else {
  165. log.error(response.getEntity().toString());
  166. throw new RuntimeException("请求错误:" + response);
  167. }
  168. } catch (org.apache.http.conn.ConnectTimeoutException cte) {
  169. log.info(url + " 请求超时。", cte);
  170. } catch (Exception e) {
  171. log.info("请求 " + url + " 失败。", e);
  172. }
  173. return result;
  174. }
  175. /**
  176. * 带请求头的 get 请求
  177. *
  178. * @param closeableHttpClient http 客户端
  179. * @param requestConfig 请求配置
  180. * @param url 请求路径带参数
  181. * @param headers 请求头
  182. * @return 请求结果
  183. * @throws IOException IO异常
  184. */
  185. public static String get(CloseableHttpClient closeableHttpClient, RequestConfig requestConfig, String url,
  186. Map<String, String> headers) throws IOException {
  187. //1 创建 post 请求
  188. HttpGet get = new HttpGet(url);
  189. //2 设置请求默认配置
  190. get.setConfig(requestConfig);
  191. //3 设置请求头 post.setHeader("Content-type", "application/json; charset=utf-8");
  192. if (!CollectionUtil.isEmpty(headers)) {
  193. headers.forEach(get::setHeader);
  194. }
  195. //4 发送请求
  196. CloseableHttpResponse response = closeableHttpClient.execute(get);
  197. //5 处理返回结果,
  198. //5-1 如果状态码为200,就是正常返回
  199. int statusCode = response.getStatusLine().getStatusCode();
  200. if (statusCode == 200) {
  201. return EntityUtils.toString(response.getEntity());
  202. } else {
  203. throw new RuntimeException("------- 请求错误:" + statusCode);
  204. }
  205. }
  206. /**
  207. * 默认请求头的 get 请求下载文件
  208. *
  209. * @param url 请求地址
  210. * @return 文件流
  211. */
  212. public static InputStream getInputStream(String url) {
  213. try {
  214. log.info("发送请求:" + url);
  215. CloseableHttpClient closeableHttpClient = getCloseableHttpClient();
  216. RequestConfig requestConfig = getRequestConfig();
  217. return getInputStream(closeableHttpClient, requestConfig, url, null);
  218. } catch (IOException e) {
  219. throw new RuntimeException(e);
  220. }
  221. }
  222. /**
  223. * 默认请求头的 get 请求下载文件
  224. *
  225. * @param url 请求地址
  226. * @return 文件流
  227. * @throws IOException 异常
  228. */
  229. public static InputStream getInputStream(CloseableHttpClient closeableHttpClient, RequestConfig requestConfig, String url) throws IOException {
  230. return getInputStream(closeableHttpClient, requestConfig, url, null);
  231. }
  232. /**
  233. * 自定义请求头的 get 请求下载文件
  234. *
  235. * @param url 请求地址
  236. * @param headers 请求头,可为 null
  237. * @return 文件流
  238. * @throws IOException 异常
  239. */
  240. public static InputStream getInputStream(CloseableHttpClient closeableHttpClient, RequestConfig requestConfig, String url, Map<String, String> headers) throws IOException {
  241. InputStream result = null;
  242. try {
  243. //1 创建 post 请求
  244. HttpGet get = new HttpGet(url);
  245. //2 设置请求默认配置
  246. get.setConfig(requestConfig);
  247. //3 设置请求头 post.setHeader("Content-type", "application/json; charset=utf-8");
  248. if (!CollectionUtil.isEmpty(headers)) {
  249. headers.forEach(get::setHeader);
  250. }
  251. //4 发送请求
  252. CloseableHttpResponse response = closeableHttpClient.execute(get);
  253. //5 处理返回结果,
  254. //5-1 如果状态码为200,就是正常返回
  255. int statusCode = response.getStatusLine().getStatusCode();
  256. log.info("请求 " + url + " 状态码为:" + statusCode);
  257. if (statusCode == 200) {
  258. result = response.getEntity().getContent();
  259. }
  260. } catch (Exception e) {
  261. log.info("请求 " + url + " 失败。", e);
  262. }
  263. return result;
  264. }
  265. /**
  266. * 自定义请求头的 post 请求
  267. */
  268. public static String post(String url, Map<String, String> headers, Map<String, String> params){
  269. log.info("发送HTTP请求:" + url+",请求参数:"+params+",请求头:"+headers);
  270. try {
  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. } catch (IOException e) {
  297. throw new RuntimeException(e);
  298. }
  299. }
  300. /**
  301. * 自定义请求头的 post 请求
  302. */
  303. public static String post(CloseableHttpClient closeableHttpClient, RequestConfig requestConfig, String url, Map<String, String> headers, Map<String, String> params) throws IOException {
  304. //1 创建 post 请求
  305. HttpPost post = new HttpPost(url);
  306. //2 设置请求默认配置
  307. post.setConfig(requestConfig);
  308. //3 设置请求头 post.setHeader("Content-type", "application/json; charset=utf-8");
  309. if (!CollectionUtil.isEmpty(headers)) {
  310. headers.forEach(post::setHeader);
  311. }
  312. //4 设置请求体
  313. post.addHeader("Content-Type", "application/json");
  314. if (!CollectionUtil.isEmpty(params)) {
  315. post.setEntity(new StringEntity(JsonUtil.beanToJson(params), "utf-8"));
  316. }
  317. //5 发送请求
  318. CloseableHttpResponse response = closeableHttpClient.execute(post);
  319. //6 处理返回结果,
  320. //6-1 如果状态码为200,就是正常返回
  321. int statusCode = response.getStatusLine().getStatusCode();
  322. if (statusCode == 200) {
  323. return EntityUtils.toString(response.getEntity());
  324. } else {
  325. throw new RuntimeException("请求错误:" + statusCode);
  326. }
  327. }
  328. //
  329. // /**
  330. // * 通过 get 请求下载文件
  331. // * 发送 get 请求,get 请求的参数在 url 里
  332. // *
  333. // * @param url 请求地址
  334. // * @param headers 请求头,可为 null
  335. // * @return 文件流
  336. // * @throws IOException 异常
  337. // */
  338. // public static InputStream getDownload(String url, Map<String, String> headers) throws IOException {
  339. // //1 创建 post 请求
  340. // HttpGet get = new HttpGet(url);
  341. // //2 设置请求默认配置
  342. // get.setConfig(requestConfig);
  343. // //3 设置请求头 post.setHeader("Content-type", "application/json; charset=utf-8");
  344. // if (!CollectionUtil.isEmpty(headers)) {
  345. // headers.forEach(get::setHeader);
  346. // }
  347. // //4 发送请求
  348. // CloseableHttpResponse response = httpClient.execute(get);
  349. // //5 处理返回结果,
  350. // //5-1 如果状态码为200,就是正常返回
  351. // int statusCode = response.getStatusLine().getStatusCode();
  352. // if (statusCode == 200) {
  353. // return response.getEntity().getContent();
  354. // } else {
  355. // throw new RuntimeException("------- 请求错误:" + statusCode);
  356. // }
  357. // }
  358. //
  359. //
  360. // /**
  361. // * 发送 post 请求
  362. // */
  363. // public static InputStream postUpload(String url) throws IOException {
  364. // //1 创建 post 请求
  365. // HttpPost post = new HttpPost(url);
  366. // //2 设置请求默认配置
  367. // post.setConfig(requestConfig);
  368. // //3 设置请求头 post.setHeader("Content-type", "application/json; charset=utf-8");
  369. // post.setHeader("Content-type", "multipart/form-data");
  370. // //5 发送请求
  371. // CloseableHttpResponse response = httpClient.execute(post);
  372. // //6 处理返回结果,
  373. // //6-1 如果状态码为 200,就是正常返回
  374. // int statusCode = response.getStatusLine().getStatusCode();
  375. // if (statusCode == 200) {
  376. // return response.getEntity().getContent();
  377. // } else {
  378. // throw new RuntimeException("------- 请求错误:" + statusCode);
  379. // }
  380. // }
  381. //
  382. // /**
  383. // * 发送 post 请求
  384. // */
  385. // public static InputStream postDownload(String url, Map<String, String> headers, Map<String, String> params) throws IOException {
  386. // //1 创建 post 请求
  387. // HttpPost post = new HttpPost(url);
  388. // //2 设置请求默认配置
  389. // post.setConfig(requestConfig);
  390. // //3 设置请求头 post.setHeader("Content-type", "application/json; charset=utf-8");
  391. // if (!CollectionUtil.isEmpty(headers)) {
  392. // headers.forEach(post::setHeader);
  393. // }
  394. // //4 设置请求体
  395. // if (!CollectionUtil.isEmpty(params)) {
  396. // params.forEach(post::setHeader);
  397. // }
  398. // //5 发送请求
  399. // CloseableHttpResponse response = httpClient.execute(post);
  400. // //6 处理返回结果,
  401. // //6-1 如果状态码为 200,就是正常返回
  402. // int statusCode = response.getStatusLine().getStatusCode();
  403. // if (statusCode == 200) {
  404. // return response.getEntity().getContent();
  405. // } else {
  406. // throw new RuntimeException("------- 请求错误:" + statusCode);
  407. // }
  408. // }
  409. }