sba应用管理
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.

914 lines
34 KiB

  1. package com.bfd.qanda.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.qanda.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, Map<String, Object>... headers){
  263. String strResult = "";
  264. //设置超时时间
  265. int timeout = 60;
  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. if (headers != null && headers.length > 0) {
  290. Map<String, Object> tempHeaders = headers[0];
  291. for (String key : tempHeaders.keySet()) {
  292. httpPost.setHeader(key, tempHeaders.get(key).toString());
  293. }
  294. } else {
  295. httpPost.addHeader("Content-Type", "application/json;charset=utf-8");
  296. }
  297. HttpResponse resp = null;
  298. try {
  299. httpPost.setEntity(new StringEntity(params,"utf-8"));
  300. resp = client.execute(httpPost);
  301. // resp = client.execute(httpPost,localContext);
  302. StatusLine statusLine = resp.getStatusLine();
  303. System.out.println("响应状态为:" + resp.getStatusLine());
  304. int notFundCode = 404;
  305. int successCode = 200;
  306. if(statusLine.getStatusCode() == successCode){
  307. // 7. 获取响应entity
  308. HttpEntity respEntity = resp.getEntity();
  309. strResult = EntityUtils.toString(respEntity, "UTF-8");
  310. if(strResult.equals(Constants.EMPTY)){
  311. strResult = "Download failed error is:reslut is null";
  312. }
  313. }else{
  314. throw new Exception("请求错误,code码为:"+statusLine.getStatusCode());
  315. }
  316. } catch (Exception e) {
  317. e.printStackTrace();
  318. strResult = "Download failed error is:"+ThrowMessageUtil.getErrmessage(e);
  319. }
  320. return strResult;
  321. }
  322. public static String httpPost(String url,String params) {
  323. String html="";
  324. html = doPost(url,params);
  325. int i = 1;
  326. while(true){
  327. if(html.contains("Download failed error is:")){
  328. log.error("DownLoadUtil------------->download is failure,url is:"+url);
  329. DateUtil.sleep(5000);
  330. i++;
  331. }else{
  332. break;
  333. }
  334. if(i > 5){
  335. break;
  336. }
  337. html = doPost(url,params);
  338. }
  339. return html;
  340. }
  341. /**
  342. * 绕过验证
  343. *
  344. * @return
  345. * @throws NoSuchAlgorithmException
  346. * @throws KeyManagementException
  347. */
  348. public static SSLContext createIgnoreVerifySSL() throws NoSuchAlgorithmException, KeyManagementException {
  349. SSLContext sc = SSLContext.getInstance("SSLv3");
  350. // 实现一个X509TrustManager接口,用于绕过验证,不用修改里面的方法
  351. X509TrustManager trustManager = new X509TrustManager() {
  352. @Override
  353. public void checkClientTrusted(
  354. java.security.cert.X509Certificate[] paramArrayOfX509Certificate,
  355. String paramString) throws CertificateException {
  356. }
  357. @Override
  358. public void checkServerTrusted(
  359. java.security.cert.X509Certificate[] paramArrayOfX509Certificate,
  360. String paramString) throws CertificateException {
  361. }
  362. @Override
  363. public java.security.cert.X509Certificate[] getAcceptedIssuers() {
  364. return null;
  365. }
  366. };
  367. sc.init(null, new TrustManager[] { trustManager }, null);
  368. return sc;
  369. }
  370. /**
  371. * 模拟请求
  372. *
  373. * @param url 资源地址
  374. * @param map 参数列表
  375. * @param encoding 编码
  376. * @return
  377. * @throws NoSuchAlgorithmException
  378. * @throws KeyManagementException
  379. * @throws IOException
  380. * @throws ClientProtocolException
  381. */
  382. public static String httpsslGet(String url,Map<String, Object> ... headers) {
  383. String html="";
  384. CloseableHttpClient client = null;
  385. HttpEntity responseEntity = null;
  386. CloseableHttpResponse response = null;
  387. try {
  388. log.debug("DownLoadUtil------------->设置下载相关信息, start....");
  389. //采用绕过验证的方式处理https请求
  390. SSLContext sslcontext = createIgnoreVerifySSL();
  391. // 设置协议http和https对应的处理socket链接工厂的对象
  392. Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
  393. .register("http", PlainConnectionSocketFactory.INSTANCE)
  394. .register("https", new SSLConnectionSocketFactory(sslcontext))
  395. .build();
  396. PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
  397. connManager.setMaxTotal(50);
  398. connManager.setDefaultMaxPerRoute(10);
  399. HttpClients.custom().setConnectionManager(connManager);
  400. //设置超时时间
  401. int timeout = 30;
  402. RequestConfig config = RequestConfig.custom().
  403. setConnectTimeout(timeout * 1000).
  404. setConnectionRequestTimeout(timeout * 1000).
  405. setSocketTimeout(timeout * 1000).build();
  406. SocketConfig socketConfig = SocketConfig.custom()
  407. .setSoKeepAlive(false)
  408. .setSoLinger(1)
  409. .setSoReuseAddress(true)
  410. .setSoTimeout(10000)
  411. .setTcpNoDelay(true).build();
  412. // 设置重定向策略
  413. LaxRedirectStrategy redirectStrategy = new LaxRedirectStrategy();
  414. //创建自定义的httpclient对象
  415. 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();
  416. // CloseableHttpClient client = HttpClients.createDefault();
  417. HttpGet httpGet = new HttpGet(url);
  418. if(headers != null && headers.length > 0){
  419. Map<String, Object> tempHeaders = headers[0];
  420. for (String key : tempHeaders.keySet()) {
  421. httpGet.setHeader(key,tempHeaders.get(key).toString());
  422. }
  423. }else{
  424. httpGet.setHeader("Accept", "application/json, text/javascript, */*; q=0.01");
  425. httpGet.setHeader("Accept-Language","zh-CN,zh;q=0.9,en;q=0.8");
  426. 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");
  427. }
  428. log.debug("DownLoadUtil------------->设置下载相关信息, end....");
  429. try {
  430. int notFundCode = 404;
  431. int successCode = 200;
  432. log.debug("DownLoadUtil------------->下载执行,start....");
  433. httpGet.setConfig(config);
  434. response = client.execute(httpGet);
  435. log.debug("DownLoadUtil------------->下载执行,end....");
  436. // 从响应模型中获取响应实体
  437. StatusLine statusLine = response.getStatusLine();
  438. log.debug("DownLoadUtil------------->响应状态为:" + response.getStatusLine()+",下载请求没问题url:"+url+",read is start ....");
  439. System.out.println("响应状态为:" + response.getStatusLine());
  440. responseEntity = response.getEntity();
  441. log.debug("DownLoadUtil------------->响应状态为:" + response.getStatusLine()+",下载请求没问题url:"+url+",read is end ....");
  442. if(statusLine.getStatusCode() == successCode){
  443. if (responseEntity != null) {
  444. html=EntityUtils.toString(responseEntity,"utf-8");
  445. System.out.println("响应内容长度为:" + responseEntity.getContentLength());
  446. }
  447. }else if(statusLine.getStatusCode() == notFundCode){
  448. html = "<h2>页面404,正常结束请求即可</h2>";
  449. }else{
  450. throw new Exception("请求错误,code码为:"+statusLine.getStatusCode());
  451. }
  452. } catch (Exception e) {
  453. e.printStackTrace();
  454. html = "Download failed error is:"+ThrowMessageUtil.getErrmessage(e);
  455. }
  456. } catch (Exception e) {
  457. e.printStackTrace();
  458. html = "Download failed error is:"+ThrowMessageUtil.getErrmessage(e);
  459. }finally{
  460. try {
  461. responseEntity.getContent().close();
  462. response.close();
  463. client.close();
  464. } catch (Exception e) {
  465. e.printStackTrace();
  466. }
  467. }
  468. return html;
  469. }
  470. public static String httpSSLGet(String url,Map<String, Object> ... headers) {
  471. String html="";
  472. html = httpsslGet(url,headers);
  473. int i = 1;
  474. while(true){
  475. if(html.contains("Download failed error is:")){
  476. log.error("DownLoadUtil------------->download is failure,url is:"+url);
  477. DateUtil.sleep(30000);
  478. i++;
  479. }else{
  480. break;
  481. }
  482. if(i > 5){
  483. break;
  484. }
  485. html = httpsslGet(url,headers);
  486. }
  487. return html;
  488. }
  489. public static String doPostFrom(String url,Map<String, Object> param,Map<String, Object> ... headers){
  490. //设置超时时间
  491. int timeout = 15;
  492. RequestConfig config = RequestConfig.custom().
  493. setConnectTimeout(timeout * 1000).
  494. setConnectionRequestTimeout(timeout * 1000).
  495. setSocketTimeout(timeout * 1000).build();
  496. SocketConfig socketConfig = SocketConfig.custom()
  497. .setSoKeepAlive(false)
  498. .setSoLinger(1)
  499. .setSoReuseAddress(true)
  500. .setSoTimeout(10000)
  501. .setTcpNoDelay(true).build();
  502. // AuthCache authCache = new BasicAuthCache();
  503. // authCache.put(proxy, new BasicScheme());
  504. // HttpClientContext localContext = HttpClientContext.create();
  505. // localContext.setAuthCache(authCache);
  506. HttpClientBuilder httpBuilder = HttpClientBuilder.create();
  507. httpBuilder.setUserAgent(ua);
  508. // HttpClient httpClient = httpBuilder.setDefaultSocketConfig(socketConfig).setDefaultRequestConfig(config).setConnectionManager(cm)
  509. // .setDefaultCredentialsProvider(credsProvider).build();
  510. HttpClient httpClient = httpBuilder.setDefaultSocketConfig(socketConfig).setDefaultRequestConfig(config).build();
  511. HttpPost httpPost = new HttpPost(url);
  512. // httpPost.setConfig(reqConfig);
  513. if(headers != null && headers.length > 0){
  514. Map<String, Object> tempHeaders = headers[0];
  515. for (String key : tempHeaders.keySet()) {
  516. httpPost.setHeader(key,tempHeaders.get(key).toString());
  517. }
  518. }else{
  519. 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");
  520. httpPost.addHeader("accept-Language", "zh-CN,zh;q=0.9,en;q=0.8");
  521. httpPost.addHeader("content-type", "application/x-www-form-urlencoded");
  522. 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");
  523. // httpPost.addHeader("Referer", "http://www.neeq.com.cn/rule/Business_rules.html");
  524. }
  525. // 创建请求参数
  526. List<NameValuePair> list = new LinkedList<>();
  527. for (String key : param.keySet()) {
  528. BasicNameValuePair param1 = new BasicNameValuePair(key,param.get(key).toString());
  529. list.add(param1);
  530. }
  531. // 使用URL实体转换工具
  532. String html="";
  533. try {
  534. UrlEncodedFormEntity entityParam = new UrlEncodedFormEntity(list, "UTF-8");
  535. httpPost.setEntity(entityParam);
  536. HttpResponse response = httpClient.execute(httpPost);
  537. // HttpResponse response = httpClient.execute(httpPost,localContext);
  538. // 从响应模型中获取响应实体
  539. HttpEntity responseEntity = response.getEntity();
  540. StatusLine statusLine = response.getStatusLine();
  541. System.out.println("响应状态为:" + response.getStatusLine());
  542. int notFundCode = 404;
  543. int successCode = 200;
  544. if(statusLine.getStatusCode() == successCode){
  545. if (responseEntity != null) {
  546. html=EntityUtils.toString(responseEntity,"utf-8");
  547. }
  548. }else{
  549. throw new Exception("请求错误,code码为:"+statusLine.getStatusCode());
  550. }
  551. } catch (Exception e) {
  552. e.printStackTrace();
  553. html = "Download failed error is:"+ThrowMessageUtil.getErrmessage(e);
  554. }
  555. return html;
  556. }
  557. public static String httpPostForm(String url,Map<String,Object> params,Map<String, Object> ... headers) {
  558. String html="";
  559. html = doPostFrom(url,params);
  560. int i = 1;
  561. while(true){
  562. if(html.contains("Download failed error is:")){
  563. log.error("DownLoadUtil------------->download is failure,url is:"+url);
  564. DateUtil.sleep(5000);
  565. i++;
  566. }else{
  567. break;
  568. }
  569. if(i > 5){
  570. break;
  571. }
  572. html = doPostFrom(url,params,headers);
  573. }
  574. return html;
  575. }
  576. public static String dosslPost(String url,String params,Map<String, Object> ... headers) {
  577. String html="";
  578. CloseableHttpClient client = null;
  579. HttpEntity responseEntity = null;
  580. CloseableHttpResponse response = null;
  581. try {
  582. //采用绕过验证的方式处理https请求
  583. SSLContext sslcontext = createIgnoreVerifySSL();
  584. // 设置协议http和https对应的处理socket链接工厂的对象
  585. Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
  586. .register("http", PlainConnectionSocketFactory.INSTANCE)
  587. .register("https", new SSLConnectionSocketFactory(sslcontext))
  588. .build();
  589. PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
  590. HttpClients.custom().setConnectionManager(connManager);
  591. //设置超时时间
  592. int timeout = 5;
  593. RequestConfig config = RequestConfig.custom().
  594. setConnectTimeout(timeout * 1000).
  595. setConnectionRequestTimeout(timeout * 1000).
  596. setSocketTimeout(timeout * 1000).build();
  597. SocketConfig socketConfig = SocketConfig.custom()
  598. .setSoKeepAlive(false)
  599. .setSoLinger(1)
  600. .setSoReuseAddress(true)
  601. .setSoTimeout(10000)
  602. .setTcpNoDelay(true).build();
  603. //创建自定义的httpclient对象
  604. client = HttpClients.custom().setConnectionManager(connManager).setDefaultRequestConfig(config).setDefaultSocketConfig(socketConfig).build();
  605. // CloseableHttpClient client = HttpClients.createDefault();
  606. // 2. 创建httppost实例
  607. HttpPost httpPost = new HttpPost(url);
  608. // httpPost.setConfig(reqConfig);
  609. httpPost.addHeader("Content-Type", "application/json;charset=utf-8");
  610. if(headers != null && headers.length > 0){
  611. Map<String, Object> tempHeaders = headers[0];
  612. for (String key : tempHeaders.keySet()) {
  613. httpPost.setHeader(key,tempHeaders.get(key).toString());
  614. }
  615. }else{
  616. httpPost.setHeader("Accept", "application/json, text/javascript, */*; q=0.01");
  617. httpPost.setHeader("Accept-Language","zh-CN,zh;q=0.9,en;q=0.8");
  618. 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");
  619. }
  620. try {
  621. httpPost.setEntity(new StringEntity(params,"utf-8"));
  622. response = client.execute(httpPost);
  623. int notFundCode = 404;
  624. int successCode = 200;
  625. // 从响应模型中获取响应实体
  626. StatusLine statusLine = response.getStatusLine();
  627. System.out.println("响应状态为:" + response.getStatusLine());
  628. responseEntity = response.getEntity();
  629. if(statusLine.getStatusCode() == successCode){
  630. if (responseEntity != null) {
  631. html=EntityUtils.toString(responseEntity,"utf-8");
  632. System.out.println("响应内容长度为:" + responseEntity.getContentLength());
  633. }
  634. }else if(statusLine.getStatusCode() == notFundCode){
  635. html = "<h2>页面404,正常结束请求即可</h2>";
  636. }else{
  637. throw new Exception("请求错误,code码为:"+statusLine.getStatusCode());
  638. }
  639. } catch (Exception e) {
  640. e.printStackTrace();
  641. html = "Download failed error is:"+ThrowMessageUtil.getErrmessage(e);
  642. }
  643. } catch (Exception e) {
  644. e.printStackTrace();
  645. html = "Download failed error is:"+ThrowMessageUtil.getErrmessage(e);
  646. }finally{
  647. try {
  648. responseEntity.getContent().close();
  649. response.close();
  650. client.close();
  651. } catch (UnsupportedOperationException e) {
  652. e.printStackTrace();
  653. } catch (IOException e) {
  654. e.printStackTrace();
  655. }
  656. }
  657. return html;
  658. }
  659. public static String dosslPostForm(String url,Map<String, Object> param,Map<String, Object> ... headers) {
  660. String html="";
  661. try {
  662. //采用绕过验证的方式处理https请求
  663. SSLContext sslcontext = createIgnoreVerifySSL();
  664. // 设置协议http和https对应的处理socket链接工厂的对象
  665. Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
  666. .register("http", PlainConnectionSocketFactory.INSTANCE)
  667. .register("https", new SSLConnectionSocketFactory(sslcontext))
  668. .build();
  669. PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
  670. HttpClients.custom().setConnectionManager(connManager);
  671. //设置超时时间
  672. int timeout = 5;
  673. RequestConfig config = RequestConfig.custom().
  674. setConnectTimeout(timeout * 1000).
  675. setConnectionRequestTimeout(timeout * 1000).
  676. setSocketTimeout(timeout * 1000).build();
  677. SocketConfig socketConfig = SocketConfig.custom()
  678. .setSoKeepAlive(false)
  679. .setSoLinger(1)
  680. .setSoReuseAddress(true)
  681. .setSoTimeout(10000)
  682. .setTcpNoDelay(true).build();
  683. //创建自定义的httpclient对象
  684. CloseableHttpClient client = HttpClients.custom().setConnectionManager(connManager).setDefaultRequestConfig(config).setDefaultSocketConfig(socketConfig).build();
  685. // CloseableHttpClient client = HttpClients.createDefault();
  686. // 2. 创建httppost实例
  687. HttpPost httpPost = new HttpPost(url);
  688. // httpPost.setConfig(reqConfig);
  689. if(headers != null && headers.length > 0){
  690. Map<String, Object> tempHeaders = headers[0];
  691. for (String key : tempHeaders.keySet()) {
  692. httpPost.setHeader(key,tempHeaders.get(key).toString());
  693. }
  694. }else{
  695. httpPost.setHeader("Accept", "application/json, text/javascript, */*; q=0.01");
  696. httpPost.setHeader("Accept-Language","zh-CN,zh;q=0.9,en;q=0.8");
  697. httpPost.addHeader("content-type", "application/x-www-form-urlencoded");
  698. 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");
  699. }
  700. // 创建请求参数
  701. List<NameValuePair> list = new LinkedList<>();
  702. for (String key : param.keySet()) {
  703. BasicNameValuePair param1 = new BasicNameValuePair(key,param.get(key).toString());
  704. list.add(param1);
  705. }
  706. // 使用URL实体转换工具
  707. try {
  708. UrlEncodedFormEntity entityParam = new UrlEncodedFormEntity(list, "UTF-8");
  709. httpPost.setEntity(entityParam);
  710. HttpResponse response = client.execute(httpPost);
  711. // HttpResponse response = httpClient.execute(httpPost,localContext);
  712. // 从响应模型中获取响应实体
  713. int notFundCode = 404;
  714. int successCode = 200;
  715. HttpEntity responseEntity = response.getEntity();
  716. StatusLine statusLine = response.getStatusLine();
  717. System.out.println("响应状态为:" + response.getStatusLine());
  718. if(statusLine.getStatusCode() == successCode){
  719. if (responseEntity != null) {
  720. html=EntityUtils.toString(responseEntity,"utf-8");
  721. }
  722. }else{
  723. throw new Exception("请求错误,code码为:"+statusLine.getStatusCode());
  724. }
  725. } catch (Exception e) {
  726. e.printStackTrace();
  727. html = "Download failed error is:"+ThrowMessageUtil.getErrmessage(e);
  728. }
  729. } catch (Exception e) {
  730. e.printStackTrace();
  731. html = "Download failed error is:"+ThrowMessageUtil.getErrmessage(e);
  732. }
  733. return html;
  734. }
  735. public static String httpSSLPostForm(String url,Map<String, Object> params,Map<String, Object> ...headers) {
  736. String html="";
  737. try {
  738. html = dosslPostForm(url,params,headers);
  739. } catch (Exception e) {
  740. e.printStackTrace();
  741. // TODO: handle exception
  742. html = "Download failed error is:Exception!";
  743. }
  744. int i = 1;
  745. while(true){
  746. if(html.contains("Download failed error is:")){
  747. log.error("DownLoadUtil------------->download is failure,url is:"+url);
  748. DateUtil.sleep(30000);
  749. i++;
  750. }else{
  751. break;
  752. }
  753. if(i > 5){
  754. break;
  755. }
  756. try {
  757. html = dosslPostForm(url,params,headers);
  758. } catch (Exception e) {
  759. e.printStackTrace();
  760. // TODO: handle exception
  761. html = "Download failed error is:Exception!";
  762. }
  763. }
  764. return html;
  765. }
  766. public static String httpSSLPost(String url,String params,Map<String, Object> ...headers) {
  767. String html="";
  768. try {
  769. html = dosslPost(url,params,headers);
  770. } catch (Throwable e) {
  771. e.printStackTrace();
  772. // TODO: handle exception
  773. html = "Download failed error is:Exception!";
  774. }
  775. int i = 1;
  776. while(true){
  777. if(html.contains("Download failed error is:")){
  778. log.error("DownLoadUtil------------->download is failure,url is:"+url);
  779. DateUtil.sleep(30000);
  780. i++;
  781. }else{
  782. break;
  783. }
  784. if(i > 5){
  785. break;
  786. }
  787. try {
  788. html = dosslPost(url,params,headers);
  789. } catch (Throwable e) {
  790. e.printStackTrace();
  791. // TODO: handle exception
  792. html = "Download failed error is:Exception!";
  793. }
  794. }
  795. return html;
  796. }
  797. /**
  798. * 模拟客户端get请求
  799. * @param url 模拟请求得url
  800. * @param headers 头部信息没有可以不传
  801. * @return
  802. */
  803. public static String doGet(String url,Map<String, Object> ... headers){
  804. //设置超时时间
  805. int timeout = 15;
  806. RequestConfig config = RequestConfig.custom().
  807. setConnectTimeout(timeout * 1000).
  808. setConnectionRequestTimeout(timeout * 1000).
  809. setSocketTimeout(timeout * 1000).build();
  810. SocketConfig socketConfig = SocketConfig.custom()
  811. .setSoKeepAlive(false)
  812. .setSoLinger(1)
  813. .setSoReuseAddress(true)
  814. .setSoTimeout(10000)
  815. .setTcpNoDelay(true).build();
  816. HttpClientBuilder httpBuilder = HttpClientBuilder.create();
  817. httpBuilder.setUserAgent(ua);
  818. HttpClient httpClient = httpBuilder.setDefaultSocketConfig(socketConfig).setDefaultRequestConfig(config).build();
  819. HttpGet httpGet = new HttpGet(url);
  820. if(headers != null && headers.length > 0){
  821. Map<String, Object> tempHeaders = headers[0];
  822. for (String key : tempHeaders.keySet()) {
  823. httpGet.setHeader(key,tempHeaders.get(key).toString());
  824. }
  825. }else{
  826. httpGet.setHeader("Accept", "application/json, text/javascript, */*; q=0.01");
  827. httpGet.setHeader("Accept-Language","zh-CN,zh;q=0.9,en;q=0.8");
  828. }
  829. String html="";
  830. try {
  831. int notFundCode = 404;
  832. int successCode = 200;
  833. HttpResponse response = httpClient.execute(httpGet);
  834. // 从响应模型中获取响应实体
  835. HttpEntity responseEntity = response.getEntity();
  836. StatusLine statusLine = response.getStatusLine();
  837. System.out.println("响应状态为:" + response.getStatusLine());
  838. if(statusLine.getStatusCode() == successCode){
  839. if (responseEntity != null) {
  840. html=EntityUtils.toString(responseEntity,"utf-8");
  841. if(html.equals("")){
  842. html = "Download failed error is:reslut is null";
  843. }
  844. }
  845. }else if(statusLine.getStatusCode() == notFundCode){
  846. html = "<h2>页面404,正常结束请求即可</h2>";
  847. }else{
  848. throw new Exception("请求错误,code码为:"+statusLine.getStatusCode());
  849. }
  850. } catch (Exception e) {
  851. e.printStackTrace();
  852. html = "Download failed error is:"+ThrowMessageUtil.getErrmessage(e);
  853. }
  854. return html;
  855. }
  856. public static void main(String[] args) throws Exception {
  857. }
  858. }