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.

1004 lines
37 KiB

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