echarts应用
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.

907 lines
34 KiB

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