opai服务管理
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

995 lines
37 KiB

  1. package com.bw.opai.utils;
  2. import java.io.File;
  3. import java.io.FileOutputStream;
  4. import java.io.IOException;
  5. import java.io.InputStream;
  6. import java.security.KeyManagementException;
  7. import java.security.NoSuchAlgorithmException;
  8. import java.security.cert.CertificateException;
  9. import java.util.LinkedList;
  10. import java.util.List;
  11. import java.util.Map;
  12. import javax.net.ssl.SSLContext;
  13. import javax.net.ssl.TrustManager;
  14. import javax.net.ssl.X509TrustManager;
  15. import org.apache.http.HttpEntity;
  16. import org.apache.http.HttpHost;
  17. import org.apache.http.HttpResponse;
  18. import org.apache.http.NameValuePair;
  19. import org.apache.http.StatusLine;
  20. import org.apache.http.auth.AuthScope;
  21. import org.apache.http.auth.UsernamePasswordCredentials;
  22. import org.apache.http.client.AuthCache;
  23. import org.apache.http.client.ClientProtocolException;
  24. import org.apache.http.client.CredentialsProvider;
  25. import org.apache.http.client.HttpClient;
  26. import org.apache.http.client.HttpRequestRetryHandler;
  27. import org.apache.http.client.config.RequestConfig;
  28. import org.apache.http.client.entity.UrlEncodedFormEntity;
  29. import org.apache.http.client.methods.CloseableHttpResponse;
  30. import org.apache.http.client.methods.HttpGet;
  31. import org.apache.http.client.methods.HttpPost;
  32. import org.apache.http.client.protocol.HttpClientContext;
  33. import org.apache.http.config.Registry;
  34. import org.apache.http.config.RegistryBuilder;
  35. import org.apache.http.config.SocketConfig;
  36. import org.apache.http.conn.socket.ConnectionSocketFactory;
  37. import org.apache.http.conn.socket.LayeredConnectionSocketFactory;
  38. import org.apache.http.conn.socket.PlainConnectionSocketFactory;
  39. import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
  40. import org.apache.http.entity.StringEntity;
  41. import org.apache.http.impl.auth.BasicScheme;
  42. import org.apache.http.impl.client.BasicAuthCache;
  43. import org.apache.http.impl.client.BasicCredentialsProvider;
  44. import org.apache.http.impl.client.CloseableHttpClient;
  45. import org.apache.http.impl.client.HttpClientBuilder;
  46. import org.apache.http.impl.client.HttpClients;
  47. import org.apache.http.impl.client.LaxRedirectStrategy;
  48. import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
  49. import org.apache.http.message.BasicNameValuePair;
  50. import org.apache.http.util.EntityUtils;
  51. import org.slf4j.Logger;
  52. import org.slf4j.LoggerFactory;
  53. /**
  54. * 下载工具类
  55. * @author jian.mao
  56. * @date 2023年9月19日
  57. * @description
  58. */
  59. public class DownLoadUtil {
  60. private static String ua = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.85 Safari/537.36";
  61. private final static Logger log = LoggerFactory.getLogger(DownLoadUtil.class);
  62. /** 代理服务器(产品官网 www.16yun.cn) **/
  63. final static String PROXYHOST = "u270.40.tp.16yun.cn";
  64. final static Integer PROXYPORT = 6448;
  65. /** 代理验证信息 **/
  66. final static String PROXYUSER = "16HFBVJC";
  67. final static String PROXYPASS = "897944";
  68. private static PoolingHttpClientConnectionManager cm = null;
  69. private static HttpRequestRetryHandler httpRequestRetryHandler = null;
  70. private static HttpHost proxy = null;
  71. private static CredentialsProvider credsProvider = null;
  72. private static RequestConfig reqConfig = null;
  73. static {
  74. ConnectionSocketFactory plainsf = PlainConnectionSocketFactory
  75. .getSocketFactory();
  76. LayeredConnectionSocketFactory sslsf = SSLConnectionSocketFactory
  77. .getSocketFactory();
  78. Registry registry = RegistryBuilder.create().register("http", plainsf)
  79. .register("https", sslsf).build();
  80. cm = new PoolingHttpClientConnectionManager(registry);
  81. cm.setMaxTotal(20);
  82. cm.setDefaultMaxPerRoute(5);
  83. proxy = new HttpHost(PROXYHOST, PROXYPORT, "https");
  84. credsProvider = new BasicCredentialsProvider();
  85. credsProvider.setCredentials(AuthScope.ANY,
  86. new UsernamePasswordCredentials(PROXYUSER, PROXYPASS));
  87. reqConfig = RequestConfig.custom().setConnectionRequestTimeout(5000)
  88. .setConnectTimeout(5000).setSocketTimeout(5000)
  89. .setExpectContinueEnabled(false)
  90. .setProxy(new HttpHost(PROXYHOST, PROXYPORT)).build();
  91. }
  92. /**
  93. * 模拟客户端get请求
  94. *
  95. * @param url
  96. * 模拟请求得url
  97. * @param headers
  98. * 头部信息没有可以不传
  99. * @return
  100. */
  101. @SafeVarargs
  102. public static String proxyDoGet(String url, Map<String, Object>... headers) {
  103. // 设置超时时间
  104. int timeout = 30;
  105. RequestConfig config = RequestConfig.custom()
  106. .setConnectTimeout(timeout * 1000)
  107. .setConnectionRequestTimeout(timeout * 1000)
  108. .setSocketTimeout(timeout * 1000).build();
  109. SocketConfig socketConfig = SocketConfig.custom()
  110. .setSoKeepAlive(false)
  111. .setSoLinger(1)
  112. .setSoReuseAddress(true)
  113. .setSoTimeout(timeout * 1000)
  114. .setTcpNoDelay(true).build();
  115. AuthCache authCache = new BasicAuthCache();
  116. authCache.put(proxy, new BasicScheme());
  117. HttpClientContext localContext = HttpClientContext.create();
  118. localContext.setAuthCache(authCache);
  119. HttpClientBuilder httpBuilder = HttpClientBuilder.create();
  120. CloseableHttpClient httpClient = httpBuilder
  121. .setDefaultSocketConfig(socketConfig)
  122. .setDefaultRequestConfig(config)
  123. .setDefaultCredentialsProvider(credsProvider).build();
  124. HttpGet httpGet = new HttpGet(url);
  125. httpGet.setConfig(reqConfig);
  126. if (headers != null && headers.length > 0) {
  127. Map<String, Object> tempHeaders = headers[0];
  128. for (String key : tempHeaders.keySet()) {
  129. httpGet.setHeader(key, tempHeaders.get(key).toString());
  130. }
  131. } else {
  132. httpGet.setHeader("Accept",
  133. "application/json, text/javascript, */*; q=0.01");
  134. httpGet.setHeader("Accept-Language", "zh-CN,zh;q=0.9,en;q=0.8");
  135. }
  136. CloseableHttpResponse response = null;
  137. String html = "";
  138. int notFundCode = 404;
  139. int successCode = 200;
  140. try {
  141. response = httpClient.execute(httpGet, localContext);
  142. // 从响应模型中获取响应实体
  143. HttpEntity responseEntity = response.getEntity();
  144. StatusLine statusLine = response.getStatusLine();
  145. System.out.println("响应状态为:" + response.getStatusLine());
  146. if (statusLine.getStatusCode() == successCode) {
  147. if (responseEntity != null) {
  148. html = EntityUtils.toString(responseEntity, "utf-8");
  149. System.out.println("响应内容长度为:"
  150. + responseEntity.getContentLength());
  151. // 下载结果为空不正常
  152. if (html.equals(Constants.EMPTY)) {
  153. html = "Download failed error is:reslut is null";
  154. }
  155. }
  156. } else if (statusLine.getStatusCode() == notFundCode) {
  157. html = "<h2>页面404,正常结束请求即可</h2>";
  158. } else {
  159. throw new Exception("请求错误,code码为:" + statusLine.getStatusCode());
  160. }
  161. } catch (Exception e) {
  162. e.printStackTrace();
  163. html = "Download failed error is:reslut is null";
  164. }finally{
  165. try {
  166. response.close();
  167. httpClient.close();
  168. } catch (Exception e) {
  169. e.printStackTrace();
  170. }
  171. }
  172. return html;
  173. }
  174. public static String httpsslProxyGet(String url, Map<String, Object>... headers) throws Exception {
  175. //采用绕过验证的方式处理https请求
  176. SSLContext sslcontext = createIgnoreVerifySSL();
  177. // 设置协议http和https对应的处理socket链接工厂的对象
  178. Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
  179. .register("http", PlainConnectionSocketFactory.INSTANCE)
  180. .register("https", new SSLConnectionSocketFactory(sslcontext))
  181. .build();
  182. PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
  183. connManager.setMaxTotal(50);
  184. connManager.setDefaultMaxPerRoute(10);
  185. HttpClients.custom().setConnectionManager(connManager);
  186. // 设置超时时间
  187. int timeout = 30;
  188. RequestConfig config = RequestConfig.custom()
  189. .setConnectTimeout(timeout * 1000)
  190. .setConnectionRequestTimeout(timeout * 1000)
  191. .setSocketTimeout(timeout * 1000).build();
  192. SocketConfig socketConfig = SocketConfig.custom()
  193. .setSoKeepAlive(false)
  194. .setSoLinger(1)
  195. .setSoReuseAddress(true)
  196. .setSoTimeout(timeout * 1000)
  197. .setTcpNoDelay(true).build();
  198. AuthCache authCache = new BasicAuthCache();
  199. authCache.put(proxy, new BasicScheme());
  200. HttpClientContext localContext = HttpClientContext.create();
  201. localContext.setAuthCache(authCache);
  202. HttpClientBuilder httpBuilder = HttpClientBuilder.create();
  203. CloseableHttpClient httpClient = httpBuilder
  204. .setConnectionManager(connManager)
  205. .setDefaultSocketConfig(socketConfig)
  206. .setDefaultRequestConfig(config)
  207. .setDefaultCredentialsProvider(credsProvider).build();
  208. HttpGet httpGet = new HttpGet(url);
  209. httpGet.setConfig(reqConfig);
  210. if (headers != null && headers.length > 0) {
  211. Map<String, Object> tempHeaders = headers[0];
  212. for (String key : tempHeaders.keySet()) {
  213. httpGet.setHeader(key, tempHeaders.get(key).toString());
  214. }
  215. } else {
  216. httpGet.setHeader("Accept",
  217. "application/json, text/javascript, */*; q=0.01");
  218. httpGet.setHeader("Accept-Language", "zh-CN,zh;q=0.9,en;q=0.8");
  219. }
  220. CloseableHttpResponse response = null;
  221. String html = "";
  222. int notFundCode = 404;
  223. int successCode = 200;
  224. try {
  225. response = httpClient.execute(httpGet, localContext);
  226. // 从响应模型中获取响应实体
  227. HttpEntity responseEntity = response.getEntity();
  228. StatusLine statusLine = response.getStatusLine();
  229. System.out.println("响应状态为:" + response.getStatusLine());
  230. if (statusLine.getStatusCode() == successCode) {
  231. if (responseEntity != null) {
  232. html = EntityUtils.toString(responseEntity, "utf-8");
  233. System.out.println("响应内容长度为:"
  234. + responseEntity.getContentLength());
  235. // 下载结果为空不正常
  236. if (html.equals(Constants.EMPTY)) {
  237. html = "Download failed error is:reslut is null";
  238. }
  239. }
  240. } else if (statusLine.getStatusCode() == notFundCode) {
  241. html = "<h2>页面404,正常结束请求即可</h2>";
  242. } else {
  243. throw new Exception("请求错误,code码为:" + statusLine.getStatusCode());
  244. }
  245. } catch (Exception e) {
  246. e.printStackTrace();
  247. html = "Download failed error is:reslut is null";
  248. }finally{
  249. try {
  250. response.close();
  251. httpClient.close();
  252. } catch (Exception e) {
  253. e.printStackTrace();
  254. }
  255. }
  256. return html;
  257. }
  258. /**
  259. * json参数方式POST提交
  260. * @param url
  261. * @param params
  262. * @return
  263. */
  264. public static String doPost(String url, String params, Map<String, Object>... headers){
  265. String strResult = "";
  266. //设置超时时间
  267. int timeout = 600;
  268. RequestConfig config = RequestConfig.custom().
  269. setConnectTimeout(timeout * 1000).
  270. setConnectionRequestTimeout(timeout * 1000).
  271. setSocketTimeout(timeout * 1000).build();
  272. SocketConfig socketConfig = SocketConfig.custom()
  273. .setSoKeepAlive(false)
  274. .setSoLinger(1)
  275. .setSoReuseAddress(true)
  276. .setSoTimeout(timeout * 1000)
  277. .setTcpNoDelay(true).build();
  278. // AuthCache authCache = new BasicAuthCache();
  279. // authCache.put(proxy, new BasicScheme());
  280. // HttpClientContext localContext = HttpClientContext.create();
  281. // localContext.setAuthCache(authCache);
  282. // 1. 获取默认的client实例
  283. HttpClientBuilder httpBuilder = HttpClientBuilder.create();
  284. httpBuilder.setUserAgent(ua);
  285. HttpClient client = httpBuilder.setDefaultSocketConfig(socketConfig).setDefaultRequestConfig(config).build();
  286. // HttpClient client = httpBuilder.setDefaultSocketConfig(socketConfig).setDefaultRequestConfig(config).setConnectionManager(cm)
  287. // .setDefaultCredentialsProvider(credsProvider).build();
  288. // 2. 创建httppost实例
  289. HttpPost httpPost = new HttpPost(url);
  290. // httpPost.setConfig(reqConfig);
  291. if (headers != null && headers.length > 0) {
  292. Map<String, Object> tempHeaders = headers[0];
  293. for (String key : tempHeaders.keySet()) {
  294. httpPost.setHeader(key, tempHeaders.get(key).toString());
  295. }
  296. } else {
  297. httpPost.addHeader("Content-Type", "application/json;charset=utf-8");
  298. }
  299. HttpResponse resp = null;
  300. try {
  301. httpPost.setEntity(new StringEntity(params,"utf-8"));
  302. resp = client.execute(httpPost);
  303. // resp = client.execute(httpPost,localContext);
  304. StatusLine statusLine = resp.getStatusLine();
  305. // System.out.println("响应状态为:" + resp.getStatusLine());
  306. int successCode = 200;
  307. if(statusLine.getStatusCode() == successCode){
  308. // 7. 获取响应entity
  309. HttpEntity respEntity = resp.getEntity();
  310. strResult = EntityUtils.toString(respEntity, "UTF-8");
  311. if(strResult.equals(Constants.EMPTY)){
  312. strResult = "Download failed error is:reslut is null";
  313. }
  314. }else{
  315. throw new Exception("请求错误,code码为:"+statusLine.getStatusCode());
  316. }
  317. } catch (Exception e) {
  318. e.printStackTrace();
  319. strResult = "Download failed error is:"+ThrowMessageUtil.getErrmessage(e);
  320. }
  321. return strResult;
  322. }
  323. public static String httpPost(String url,String params) {
  324. String html="";
  325. html = doPost(url,params);
  326. int i = 1;
  327. while(true){
  328. if(html.contains("Download failed error is:")){
  329. log.error("DownLoadUtil------------->download is failure,url is:"+url);
  330. DateUtil.sleep(5000);
  331. i++;
  332. }else{
  333. break;
  334. }
  335. if(i > 5){
  336. break;
  337. }
  338. html = doPost(url,params);
  339. }
  340. return html;
  341. }
  342. /**
  343. * 绕过验证
  344. *
  345. * @return
  346. * @throws NoSuchAlgorithmException
  347. * @throws KeyManagementException
  348. */
  349. public static SSLContext createIgnoreVerifySSL() throws NoSuchAlgorithmException, KeyManagementException {
  350. SSLContext sc = SSLContext.getInstance("SSLv3");
  351. // 实现一个X509TrustManager接口,用于绕过验证,不用修改里面的方法
  352. X509TrustManager trustManager = new X509TrustManager() {
  353. @Override
  354. public void checkClientTrusted(
  355. java.security.cert.X509Certificate[] paramArrayOfX509Certificate,
  356. String paramString) throws CertificateException {
  357. }
  358. @Override
  359. public void checkServerTrusted(
  360. java.security.cert.X509Certificate[] paramArrayOfX509Certificate,
  361. String paramString) throws CertificateException {
  362. }
  363. @Override
  364. public java.security.cert.X509Certificate[] getAcceptedIssuers() {
  365. return null;
  366. }
  367. };
  368. sc.init(null, new TrustManager[] { trustManager }, null);
  369. return sc;
  370. }
  371. /**
  372. * 模拟请求
  373. *
  374. * @param url 资源地址
  375. * @param map 参数列表
  376. * @param encoding 编码
  377. * @return
  378. * @throws NoSuchAlgorithmException
  379. * @throws KeyManagementException
  380. * @throws IOException
  381. * @throws ClientProtocolException
  382. */
  383. public static String httpsslGet(String url,Map<String, Object> ... headers) {
  384. String html="";
  385. CloseableHttpClient client = null;
  386. HttpEntity responseEntity = null;
  387. CloseableHttpResponse response = null;
  388. try {
  389. log.debug("DownLoadUtil------------->设置下载相关信息, start....");
  390. //采用绕过验证的方式处理https请求
  391. SSLContext sslcontext = createIgnoreVerifySSL();
  392. // 设置协议http和https对应的处理socket链接工厂的对象
  393. Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
  394. .register("http", PlainConnectionSocketFactory.INSTANCE)
  395. .register("https", new SSLConnectionSocketFactory(sslcontext))
  396. .build();
  397. PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
  398. connManager.setMaxTotal(50);
  399. connManager.setDefaultMaxPerRoute(10);
  400. HttpClients.custom().setConnectionManager(connManager);
  401. //设置超时时间
  402. int timeout = 30;
  403. RequestConfig config = RequestConfig.custom().
  404. setConnectTimeout(timeout * 1000).
  405. setConnectionRequestTimeout(timeout * 1000).
  406. setSocketTimeout(timeout * 1000).build();
  407. SocketConfig socketConfig = SocketConfig.custom()
  408. .setSoKeepAlive(false)
  409. .setSoLinger(1)
  410. .setSoReuseAddress(true)
  411. .setSoTimeout(10000)
  412. .setTcpNoDelay(true).build();
  413. // 设置重定向策略
  414. LaxRedirectStrategy redirectStrategy = new LaxRedirectStrategy();
  415. //创建自定义的httpclient对象
  416. client = HttpClients.custom().setConnectionManager(connManager).setDefaultRequestConfig(config).setRedirectStrategy(redirectStrategy).setDefaultSocketConfig(socketConfig).setUserAgent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.77 Safari/537.36").build();
  417. // CloseableHttpClient client = HttpClients.createDefault();
  418. HttpGet httpGet = new HttpGet(url);
  419. if(headers != null && headers.length > 0){
  420. Map<String, Object> tempHeaders = headers[0];
  421. for (String key : tempHeaders.keySet()) {
  422. httpGet.setHeader(key,tempHeaders.get(key).toString());
  423. }
  424. }else{
  425. httpGet.setHeader("Accept", "application/json, text/javascript, */*; q=0.01");
  426. httpGet.setHeader("Accept-Language","zh-CN,zh;q=0.9,en;q=0.8");
  427. httpGet.setHeader("User-Agent","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.77 Safari/537.36");
  428. }
  429. log.debug("DownLoadUtil------------->设置下载相关信息, end....");
  430. try {
  431. int notFundCode = 404;
  432. int successCode = 200;
  433. log.debug("DownLoadUtil------------->下载执行,start....");
  434. httpGet.setConfig(config);
  435. response = client.execute(httpGet);
  436. log.debug("DownLoadUtil------------->下载执行,end....");
  437. // 从响应模型中获取响应实体
  438. StatusLine statusLine = response.getStatusLine();
  439. log.debug("DownLoadUtil------------->响应状态为:" + response.getStatusLine()+",下载请求没问题url:"+url+",read is start ....");
  440. System.out.println("响应状态为:" + response.getStatusLine());
  441. responseEntity = response.getEntity();
  442. log.debug("DownLoadUtil------------->响应状态为:" + response.getStatusLine()+",下载请求没问题url:"+url+",read is end ....");
  443. if(statusLine.getStatusCode() == successCode){
  444. if (responseEntity != null) {
  445. html=EntityUtils.toString(responseEntity,"utf-8");
  446. System.out.println("响应内容长度为:" + responseEntity.getContentLength());
  447. }
  448. }else if(statusLine.getStatusCode() == notFundCode){
  449. html = "<h2>页面404,正常结束请求即可</h2>";
  450. }else{
  451. throw new Exception("请求错误,code码为:"+statusLine.getStatusCode());
  452. }
  453. } catch (Exception e) {
  454. e.printStackTrace();
  455. html = "Download failed error is:"+ThrowMessageUtil.getErrmessage(e);
  456. }
  457. } catch (Exception e) {
  458. e.printStackTrace();
  459. html = "Download failed error is:"+ThrowMessageUtil.getErrmessage(e);
  460. }finally{
  461. try {
  462. responseEntity.getContent().close();
  463. response.close();
  464. client.close();
  465. } catch (Exception e) {
  466. e.printStackTrace();
  467. }
  468. }
  469. return html;
  470. }
  471. public static String httpSSLGet(String url,Map<String, Object> ... headers) {
  472. String html="";
  473. html = httpsslGet(url,headers);
  474. int i = 1;
  475. while(true){
  476. if(html.contains("Download failed error is:")){
  477. log.error("DownLoadUtil------------->download is failure,url is:"+url);
  478. DateUtil.sleep(30000);
  479. i++;
  480. }else{
  481. break;
  482. }
  483. if(i > 5){
  484. break;
  485. }
  486. html = httpsslGet(url,headers);
  487. }
  488. return html;
  489. }
  490. public static String doPostFrom(String url,Map<String, Object> param,Map<String, Object> ... headers){
  491. //设置超时时间
  492. int timeout = 15;
  493. RequestConfig config = RequestConfig.custom().
  494. setConnectTimeout(timeout * 1000).
  495. setConnectionRequestTimeout(timeout * 1000).
  496. setSocketTimeout(timeout * 1000).build();
  497. SocketConfig socketConfig = SocketConfig.custom()
  498. .setSoKeepAlive(false)
  499. .setSoLinger(1)
  500. .setSoReuseAddress(true)
  501. .setSoTimeout(10000)
  502. .setTcpNoDelay(true).build();
  503. // AuthCache authCache = new BasicAuthCache();
  504. // authCache.put(proxy, new BasicScheme());
  505. // HttpClientContext localContext = HttpClientContext.create();
  506. // localContext.setAuthCache(authCache);
  507. HttpClientBuilder httpBuilder = HttpClientBuilder.create();
  508. httpBuilder.setUserAgent(ua);
  509. // HttpClient httpClient = httpBuilder.setDefaultSocketConfig(socketConfig).setDefaultRequestConfig(config).setConnectionManager(cm)
  510. // .setDefaultCredentialsProvider(credsProvider).build();
  511. HttpClient httpClient = httpBuilder.setDefaultSocketConfig(socketConfig).setDefaultRequestConfig(config).build();
  512. HttpPost httpPost = new HttpPost(url);
  513. // httpPost.setConfig(reqConfig);
  514. if(headers != null && headers.length > 0){
  515. Map<String, Object> tempHeaders = headers[0];
  516. for (String key : tempHeaders.keySet()) {
  517. httpPost.setHeader(key,tempHeaders.get(key).toString());
  518. }
  519. }else{
  520. httpPost.addHeader("accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9");
  521. httpPost.addHeader("accept-Language", "zh-CN,zh;q=0.9,en;q=0.8");
  522. httpPost.addHeader("content-type", "application/x-www-form-urlencoded");
  523. httpPost.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.149 Safari/537.36");
  524. // httpPost.addHeader("Referer", "http://www.neeq.com.cn/rule/Business_rules.html");
  525. }
  526. // 创建请求参数
  527. List<NameValuePair> list = new LinkedList<>();
  528. for (String key : param.keySet()) {
  529. BasicNameValuePair param1 = new BasicNameValuePair(key,param.get(key).toString());
  530. list.add(param1);
  531. }
  532. // 使用URL实体转换工具
  533. String html="";
  534. try {
  535. UrlEncodedFormEntity entityParam = new UrlEncodedFormEntity(list, "UTF-8");
  536. httpPost.setEntity(entityParam);
  537. HttpResponse response = httpClient.execute(httpPost);
  538. // HttpResponse response = httpClient.execute(httpPost,localContext);
  539. // 从响应模型中获取响应实体
  540. HttpEntity responseEntity = response.getEntity();
  541. StatusLine statusLine = response.getStatusLine();
  542. System.out.println("响应状态为:" + response.getStatusLine());
  543. int notFundCode = 404;
  544. int successCode = 200;
  545. if(statusLine.getStatusCode() == successCode){
  546. if (responseEntity != null) {
  547. html=EntityUtils.toString(responseEntity,"utf-8");
  548. }
  549. }else{
  550. throw new Exception("请求错误,code码为:"+statusLine.getStatusCode());
  551. }
  552. } catch (Exception e) {
  553. e.printStackTrace();
  554. html = "Download failed error is:"+ThrowMessageUtil.getErrmessage(e);
  555. }
  556. return html;
  557. }
  558. public static String httpPostForm(String url,Map<String,Object> params,Map<String, Object> ... headers) {
  559. String html="";
  560. html = doPostFrom(url,params);
  561. int i = 1;
  562. while(true){
  563. if(html.contains("Download failed error is:")){
  564. log.error("DownLoadUtil------------->download is failure,url is:"+url);
  565. DateUtil.sleep(5000);
  566. i++;
  567. }else{
  568. break;
  569. }
  570. if(i > 5){
  571. break;
  572. }
  573. html = doPostFrom(url,params,headers);
  574. }
  575. return html;
  576. }
  577. public static String dosslPost(String url,String params,Map<String, Object> ... headers) {
  578. String html="";
  579. CloseableHttpClient client = null;
  580. HttpEntity responseEntity = null;
  581. CloseableHttpResponse response = null;
  582. try {
  583. //采用绕过验证的方式处理https请求
  584. SSLContext sslcontext = createIgnoreVerifySSL();
  585. // 设置协议http和https对应的处理socket链接工厂的对象
  586. Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
  587. .register("http", PlainConnectionSocketFactory.INSTANCE)
  588. .register("https", new SSLConnectionSocketFactory(sslcontext))
  589. .build();
  590. PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
  591. HttpClients.custom().setConnectionManager(connManager);
  592. //设置超时时间
  593. int timeout = 5;
  594. RequestConfig config = RequestConfig.custom().
  595. setConnectTimeout(timeout * 1000).
  596. setConnectionRequestTimeout(timeout * 1000).
  597. setSocketTimeout(timeout * 1000).build();
  598. SocketConfig socketConfig = SocketConfig.custom()
  599. .setSoKeepAlive(false)
  600. .setSoLinger(1)
  601. .setSoReuseAddress(true)
  602. .setSoTimeout(10000)
  603. .setTcpNoDelay(true).build();
  604. //创建自定义的httpclient对象
  605. client = HttpClients.custom().setConnectionManager(connManager).setDefaultRequestConfig(config).setDefaultSocketConfig(socketConfig).build();
  606. // CloseableHttpClient client = HttpClients.createDefault();
  607. // 2. 创建httppost实例
  608. HttpPost httpPost = new HttpPost(url);
  609. // httpPost.setConfig(reqConfig);
  610. httpPost.addHeader("Content-Type", "application/json;charset=utf-8");
  611. if(headers != null && headers.length > 0){
  612. Map<String, Object> tempHeaders = headers[0];
  613. for (String key : tempHeaders.keySet()) {
  614. httpPost.setHeader(key,tempHeaders.get(key).toString());
  615. }
  616. }else{
  617. httpPost.setHeader("Accept", "application/json, text/javascript, */*; q=0.01");
  618. httpPost.setHeader("Accept-Language","zh-CN,zh;q=0.9,en;q=0.8");
  619. httpPost.setHeader("User-Agent","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.77 Safari/537.36");
  620. }
  621. try {
  622. httpPost.setEntity(new StringEntity(params,"utf-8"));
  623. response = client.execute(httpPost);
  624. int notFundCode = 404;
  625. int successCode = 200;
  626. // 从响应模型中获取响应实体
  627. StatusLine statusLine = response.getStatusLine();
  628. System.out.println("响应状态为:" + response.getStatusLine());
  629. responseEntity = response.getEntity();
  630. if(statusLine.getStatusCode() == successCode){
  631. if (responseEntity != null) {
  632. html=EntityUtils.toString(responseEntity,"utf-8");
  633. System.out.println("响应内容长度为:" + responseEntity.getContentLength());
  634. }
  635. }else if(statusLine.getStatusCode() == notFundCode){
  636. html = "<h2>页面404,正常结束请求即可</h2>";
  637. }else{
  638. throw new Exception("请求错误,code码为:"+statusLine.getStatusCode());
  639. }
  640. } catch (Exception e) {
  641. e.printStackTrace();
  642. html = "Download failed error is:"+ThrowMessageUtil.getErrmessage(e);
  643. }
  644. } catch (Exception e) {
  645. e.printStackTrace();
  646. html = "Download failed error is:"+ThrowMessageUtil.getErrmessage(e);
  647. }finally{
  648. try {
  649. responseEntity.getContent().close();
  650. response.close();
  651. client.close();
  652. } catch (UnsupportedOperationException e) {
  653. e.printStackTrace();
  654. } catch (IOException e) {
  655. e.printStackTrace();
  656. }
  657. }
  658. return html;
  659. }
  660. public static String dosslPostForm(String url,Map<String, Object> param,Map<String, Object> ... headers) {
  661. String html="";
  662. try {
  663. //采用绕过验证的方式处理https请求
  664. SSLContext sslcontext = createIgnoreVerifySSL();
  665. // 设置协议http和https对应的处理socket链接工厂的对象
  666. Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
  667. .register("http", PlainConnectionSocketFactory.INSTANCE)
  668. .register("https", new SSLConnectionSocketFactory(sslcontext))
  669. .build();
  670. PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
  671. HttpClients.custom().setConnectionManager(connManager);
  672. //设置超时时间
  673. int timeout = 5;
  674. RequestConfig config = RequestConfig.custom().
  675. setConnectTimeout(timeout * 1000).
  676. setConnectionRequestTimeout(timeout * 1000).
  677. setSocketTimeout(timeout * 1000).build();
  678. SocketConfig socketConfig = SocketConfig.custom()
  679. .setSoKeepAlive(false)
  680. .setSoLinger(1)
  681. .setSoReuseAddress(true)
  682. .setSoTimeout(10000)
  683. .setTcpNoDelay(true).build();
  684. //创建自定义的httpclient对象
  685. CloseableHttpClient client = HttpClients.custom().setConnectionManager(connManager).setDefaultRequestConfig(config).setDefaultSocketConfig(socketConfig).build();
  686. // CloseableHttpClient client = HttpClients.createDefault();
  687. // 2. 创建httppost实例
  688. HttpPost httpPost = new HttpPost(url);
  689. // httpPost.setConfig(reqConfig);
  690. if(headers != null && headers.length > 0){
  691. Map<String, Object> tempHeaders = headers[0];
  692. for (String key : tempHeaders.keySet()) {
  693. httpPost.setHeader(key,tempHeaders.get(key).toString());
  694. }
  695. }else{
  696. httpPost.setHeader("Accept", "application/json, text/javascript, */*; q=0.01");
  697. httpPost.setHeader("Accept-Language","zh-CN,zh;q=0.9,en;q=0.8");
  698. httpPost.addHeader("content-type", "application/x-www-form-urlencoded");
  699. httpPost.setHeader("User-Agent","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.77 Safari/537.36");
  700. }
  701. // 创建请求参数
  702. List<NameValuePair> list = new LinkedList<>();
  703. for (String key : param.keySet()) {
  704. BasicNameValuePair param1 = new BasicNameValuePair(key,param.get(key).toString());
  705. list.add(param1);
  706. }
  707. // 使用URL实体转换工具
  708. try {
  709. UrlEncodedFormEntity entityParam = new UrlEncodedFormEntity(list, "UTF-8");
  710. httpPost.setEntity(entityParam);
  711. HttpResponse response = client.execute(httpPost);
  712. // HttpResponse response = httpClient.execute(httpPost,localContext);
  713. // 从响应模型中获取响应实体
  714. int notFundCode = 404;
  715. int successCode = 200;
  716. HttpEntity responseEntity = response.getEntity();
  717. StatusLine statusLine = response.getStatusLine();
  718. System.out.println("响应状态为:" + response.getStatusLine());
  719. if(statusLine.getStatusCode() == successCode){
  720. if (responseEntity != null) {
  721. html=EntityUtils.toString(responseEntity,"utf-8");
  722. }
  723. }else{
  724. throw new Exception("请求错误,code码为:"+statusLine.getStatusCode());
  725. }
  726. } catch (Exception e) {
  727. e.printStackTrace();
  728. html = "Download failed error is:"+ThrowMessageUtil.getErrmessage(e);
  729. }
  730. } catch (Exception e) {
  731. e.printStackTrace();
  732. html = "Download failed error is:"+ThrowMessageUtil.getErrmessage(e);
  733. }
  734. return html;
  735. }
  736. public static String httpSSLPostForm(String url,Map<String, Object> params,Map<String, Object> ...headers) {
  737. String html="";
  738. try {
  739. html = dosslPostForm(url,params,headers);
  740. } catch (Exception e) {
  741. e.printStackTrace();
  742. // TODO: handle exception
  743. html = "Download failed error is:Exception!";
  744. }
  745. int i = 1;
  746. while(true){
  747. if(html.contains("Download failed error is:")){
  748. log.error("DownLoadUtil------------->download is failure,url is:"+url);
  749. DateUtil.sleep(30000);
  750. i++;
  751. }else{
  752. break;
  753. }
  754. if(i > 5){
  755. break;
  756. }
  757. try {
  758. html = dosslPostForm(url,params,headers);
  759. } catch (Exception e) {
  760. e.printStackTrace();
  761. // TODO: handle exception
  762. html = "Download failed error is:Exception!";
  763. }
  764. }
  765. return html;
  766. }
  767. public static String httpSSLPost(String url,String params,Map<String, Object> ...headers) {
  768. String html="";
  769. try {
  770. html = dosslPost(url,params,headers);
  771. } catch (Throwable e) {
  772. e.printStackTrace();
  773. // TODO: handle exception
  774. html = "Download failed error is:Exception!";
  775. }
  776. int i = 1;
  777. while(true){
  778. if(html.contains("Download failed error is:")){
  779. log.error("DownLoadUtil------------->download is failure,url is:"+url);
  780. DateUtil.sleep(30000);
  781. i++;
  782. }else{
  783. break;
  784. }
  785. if(i > 5){
  786. break;
  787. }
  788. try {
  789. html = dosslPost(url,params,headers);
  790. } catch (Throwable e) {
  791. e.printStackTrace();
  792. // TODO: handle exception
  793. html = "Download failed error is:Exception!";
  794. }
  795. }
  796. return html;
  797. }
  798. /**
  799. * 模拟客户端get请求
  800. * @param url 模拟请求得url
  801. * @param headers 头部信息没有可以不传
  802. * @return
  803. */
  804. public static String doGet(String url,Map<String, Object> ... headers){
  805. //设置超时时间
  806. int timeout = 15;
  807. RequestConfig config = RequestConfig.custom().
  808. setConnectTimeout(timeout * 1000).
  809. setConnectionRequestTimeout(timeout * 1000).
  810. setSocketTimeout(timeout * 1000).build();
  811. SocketConfig socketConfig = SocketConfig.custom()
  812. .setSoKeepAlive(false)
  813. .setSoLinger(1)
  814. .setSoReuseAddress(true)
  815. .setSoTimeout(10000)
  816. .setTcpNoDelay(true).build();
  817. HttpClientBuilder httpBuilder = HttpClientBuilder.create();
  818. httpBuilder.setUserAgent(ua);
  819. HttpClient httpClient = httpBuilder.setDefaultSocketConfig(socketConfig).setDefaultRequestConfig(config).build();
  820. HttpGet httpGet = new HttpGet(url);
  821. if(headers != null && headers.length > 0){
  822. Map<String, Object> tempHeaders = headers[0];
  823. for (String key : tempHeaders.keySet()) {
  824. httpGet.setHeader(key,tempHeaders.get(key).toString());
  825. }
  826. }else{
  827. httpGet.setHeader("Accept", "application/json, text/javascript, */*; q=0.01");
  828. httpGet.setHeader("Accept-Language","zh-CN,zh;q=0.9,en;q=0.8");
  829. }
  830. String html="";
  831. try {
  832. int notFundCode = 404;
  833. int successCode = 200;
  834. HttpResponse response = httpClient.execute(httpGet);
  835. // 从响应模型中获取响应实体
  836. HttpEntity responseEntity = response.getEntity();
  837. StatusLine statusLine = response.getStatusLine();
  838. System.out.println("响应状态为:" + response.getStatusLine());
  839. if(statusLine.getStatusCode() == successCode){
  840. if (responseEntity != null) {
  841. html=EntityUtils.toString(responseEntity,"utf-8");
  842. if(html.equals("")){
  843. html = "Download failed error is:reslut is null";
  844. }
  845. }
  846. }else if(statusLine.getStatusCode() == notFundCode){
  847. html = "<h2>页面404,正常结束请求即可</h2>";
  848. }else{
  849. throw new Exception("请求错误,code码为:"+statusLine.getStatusCode());
  850. }
  851. } catch (Exception e) {
  852. e.printStackTrace();
  853. html = "Download failed error is:"+ThrowMessageUtil.getErrmessage(e);
  854. }
  855. return html;
  856. }
  857. /**
  858. * 文件下载
  859. * @param fileURL 文件连接
  860. * @param saveFilePath 文件存储地址
  861. * @throws IOException
  862. */
  863. public static void downloadFile(String fileURL, String saveFilePath,Map<String, Object> ... headers) {
  864. //设置超时时间
  865. int timeout = 60;
  866. RequestConfig config = RequestConfig.custom().
  867. setConnectTimeout(timeout * 1000).
  868. setConnectionRequestTimeout(timeout * 1000).
  869. setSocketTimeout(timeout * 1000).build();
  870. SocketConfig socketConfig = SocketConfig.custom()
  871. .setSoKeepAlive(false)
  872. .setSoLinger(1)
  873. .setSoReuseAddress(true)
  874. .setSoTimeout(timeout * 1000)
  875. .setTcpNoDelay(true).build();
  876. HttpClientBuilder httpBuilder = HttpClientBuilder.create();
  877. httpBuilder.setUserAgent(ua);
  878. HttpClient httpClient = httpBuilder.setDefaultSocketConfig(socketConfig).setDefaultRequestConfig(config).build();
  879. HttpGet httpGet = new HttpGet(fileURL);
  880. if(headers != null && headers.length > 0){
  881. Map<String, Object> tempHeaders = headers[0];
  882. for (String key : tempHeaders.keySet()) {
  883. httpGet.setHeader(key,tempHeaders.get(key).toString());
  884. }
  885. }else{
  886. httpGet.setHeader("Accept", "application/json, text/javascript, */*; q=0.01");
  887. httpGet.setHeader("Accept-Language","zh-CN,zh;q=0.9,en;q=0.8");
  888. }
  889. try {
  890. int successCode = 200;
  891. HttpResponse response = httpClient.execute(httpGet);
  892. // 从响应模型中获取响应实体
  893. StatusLine statusLine = response.getStatusLine();
  894. int statusCode = statusLine.getStatusCode();
  895. if(statusCode == successCode){
  896. // 获取响应体
  897. HttpEntity entity = response.getEntity();
  898. if (entity != null) {
  899. // 创建输入流来读取文件内容
  900. try (InputStream inputStream = entity.getContent();
  901. FileOutputStream fileOutputStream = new FileOutputStream(new File(saveFilePath))) {
  902. byte[] buffer = new byte[4096];
  903. int bytesRead;
  904. while ((bytesRead = inputStream.read(buffer)) != -1) {
  905. fileOutputStream.write(buffer, 0, bytesRead);
  906. }
  907. }
  908. log.info("文件下载成功,保存路径为: {}" , saveFilePath);
  909. }
  910. } else {
  911. log.error("文件下载失败,HTTP 响应状态码为: {}" , statusCode);
  912. }
  913. EntityUtils.consume(response.getEntity());
  914. } catch (Exception e) {
  915. log.error("下载文件异常:{}",e);
  916. }
  917. }
  918. /**
  919. * 删除文件
  920. * @param filePath
  921. */
  922. public static void delFile(String filePath) {
  923. try {
  924. // 创建 File 对象
  925. File file = new File(filePath);
  926. // 检查文件是否存在
  927. if (file.exists()) {
  928. // 尝试删除文件
  929. if (file.delete()) {
  930. log.info("文件删除成功: " + filePath);
  931. } else {
  932. log.error("无法删除文件: " + filePath);
  933. }
  934. } else {
  935. log.warn("文件不存在: " + filePath);
  936. }
  937. } catch (Exception e) {
  938. // TODO: handle exception
  939. log.error("删除文件异常:{}",filePath);
  940. }
  941. }
  942. }