minimax大模型
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.

1070 lines
40 KiB

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