1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171
| `package com.ruoyi.web.controller.meetingminutes.utils;
/** * @Author 不要有情绪的 ljy * @Date 2024/10/31 20:34 * @Description: */
import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InterruptedIOException; import java.net.Authenticator; import java.net.InetSocketAddress; import java.net.MalformedURLException; import java.net.PasswordAuthentication; import java.net.Proxy; import java.net.Socket; import java.net.UnknownHostException; import java.security.KeyManagementException; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.TimerTask; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit;
import javax.net.ssl.SSLContext; import javax.net.ssl.SSLException; import javax.net.ssl.SSLHandshakeException;
import org.apache.commons.codec.CharEncoding; import org.apache.commons.io.IOUtils; import org.apache.http.Consts; import org.apache.http.HttpEntity; import org.apache.http.HttpEntityEnclosingRequest; import org.apache.http.HttpHost; import org.apache.http.HttpRequest; import org.apache.http.NameValuePair; import org.apache.http.NoHttpResponseException; import org.apache.http.auth.AUTH; import org.apache.http.auth.AuthState; import org.apache.http.auth.MalformedChallengeException; import org.apache.http.auth.UsernamePasswordCredentials; import org.apache.http.client.HttpRequestRetryHandler; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpPut; import org.apache.http.client.protocol.HttpClientContext; import org.apache.http.config.Registry; import org.apache.http.config.RegistryBuilder; import org.apache.http.conn.ConnectTimeoutException; import org.apache.http.conn.socket.ConnectionSocketFactory; import org.apache.http.conn.socket.LayeredConnectionSocketFactory; import org.apache.http.conn.socket.PlainConnectionSocketFactory; import org.apache.http.conn.ssl.NoopHostnameVerifier; import org.apache.http.conn.ssl.SSLConnectionSocketFactory; import org.apache.http.conn.ssl.TrustStrategy; import org.apache.http.entity.ContentType; import org.apache.http.entity.StringEntity; import org.apache.http.entity.mime.MultipartEntityBuilder; import org.apache.http.entity.mime.content.InputStreamBody; import org.apache.http.entity.mime.content.StringBody; import org.apache.http.impl.auth.BasicScheme; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.apache.http.message.BasicHeader; import org.apache.http.message.BasicNameValuePair; import org.apache.http.protocol.HttpContext; import org.apache.http.ssl.SSLContextBuilder; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
/** * httpclient Sock5支持参考:https://blog.csdn.net/weixin_34075268/article/details/92040047 * @author liujh * */ publicclass HttpsKitWithProxyAuth {
privatestatic Logger logger = LoggerFactory.getLogger(HttpsKitWithProxyAuth.class); privatestaticfinalint CONNECT_TIMEOUT = 10000;// 设置连接建立的超时时间为10000ms privatestaticfinalint SOCKET_TIMEOUT = 30000; // 多少时间没有数据传输 privatestaticfinalint HttpIdelTimeout = 30000;//空闲时间 privatestaticfinalint HttpMonitorInterval = 10000;//多久检查一次 privatestaticfinalint MAX_CONN = 200; // 最大连接数 privatestaticfinalint Max_PRE_ROUTE = 200; //设置到路由的最大连接数, privatestatic CloseableHttpClient httpClient; // 发送请求的客户端单例 privatestatic PoolingHttpClientConnectionManager manager; // 连接池管理类 privatestatic ScheduledExecutorService monitorExecutor;
privatestaticfinal String APPLICATION_FORM_URLENCODED = "application/x-www-form-urlencoded"; privatestaticfinal String APPLICATION_JSON = "application/json"; privatestaticfinal String USER_AGENT = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36"; privatestaticfinal Object syncLock = new Object(); // 相当于线程锁,用于线程安全
/** * 代理相关的变量, */ publicstaticfinal String HTTP = "http";//proxyType的取值之一http publicstaticfinal String SOCKS = "socks";//proxyType的取值之一socks privatestaticboolean needProxy = false; //是否需要代理连接 privatestaticboolean needLogin = false;//代理连接是否需要账号和密码,为true时填上proxyUsername和proxyPassword privatestatic String proxyType = HTTP; //代理类型,http,socks分别为http代理和sock5代理 privatestatic String proxyHost = "127.0.0.1"; //代理IP privatestaticint proxyPort = 1080; //代理端口 privatestatic String proxyUsername = "sendi";//代理账号,needLogin为true时不能为空 privatestatic String proxyPassword = "123456";//代理密码,needLogin为true时不能为空
privatestatic RequestConfig requestConfig = RequestConfig.custom() .setConnectionRequestTimeout(CONNECT_TIMEOUT) .setConnectTimeout(CONNECT_TIMEOUT) //.setCookieSpec(CookieSpecs.IGNORE_COOKIES) .setSocketTimeout(SOCKET_TIMEOUT).build();
static { /** * Sock5代理账号和密码设置 * 如果账号和密码都不为空表示需要账号密码认证,因为这个是全局生效,因此在这里直接设置 * 可通过Authenticator.setDefault(null)取消全局配置 * Authenticator.setDefault(Authenticator a)关于a参数的说明如下: * (The authenticator to be set. If a is {@code null} then any previously set authenticator is removed.) */ if(needProxy && SOCKS.equals(proxyType) && needLogin){ //用户名和密码验证 Authenticator.setDefault(new Authenticator(){ protected PasswordAuthentication getPasswordAuthentication(){ PasswordAuthentication p = new PasswordAuthentication(proxyUsername, proxyPassword.toCharArray()); return p; } }); } }
/** * 设置代理信息,可以在发请求前进行调用,用于替换此类中的代理相关的变量,全局设置一次就可 * needProxy 是否需要代理连接 * needLogin 代理连接是否需要账号和密码,为true时填上proxyUsername和proxyPassword * proxyType 代理类型,http,socks分别为http代理和sock5代理 * proxyHost 代理IP * proxyPort 代理端口 * proxyUsername 代理账号,needLogin为true时不能为空 * proxyPassword 代理密码,needLogin为true时不能为空 */ public static void setProxy(boolean needProxy,boolean needLogin,String proxyType,String proxyHost,int proxyPort,String proxyUserName,String proxyPassword){
HttpsKitWithProxyAuth.needProxy = needProxy; HttpsKitWithProxyAuth.needLogin = needLogin; HttpsKitWithProxyAuth.proxyType = proxyType; HttpsKitWithProxyAuth.proxyHost = proxyHost; HttpsKitWithProxyAuth.proxyPort = proxyPort; HttpsKitWithProxyAuth.proxyUsername = proxyUserName; HttpsKitWithProxyAuth.proxyPassword = proxyPassword;
}
private static CloseableHttpClient getHttpClient() {
if (httpClient == null) { // 多线程下多个线程同时调用getHttpClient容易导致重复创建httpClient对象的问题,所以加上了同步锁 synchronized (syncLock) { if (httpClient == null) {
try { httpClient = createHttpClient(); } catch (KeyManagementException e) { logger.error("error",e); } catch (NoSuchAlgorithmException e) { logger.error("error",e); } catch (KeyStoreException e) { logger.error("error",e); }
// 开启监控线程,对异常和空闲线程进行关闭 monitorExecutor = Executors.newScheduledThreadPool(1); monitorExecutor.scheduleAtFixedRate(new TimerTask() { @Override public void run() {
// 关闭异常连接 manager.closeExpiredConnections();
// 关闭5s空闲的连接 manager.closeIdleConnections(HttpIdelTimeout,TimeUnit.MILLISECONDS);
//logger.info(manager.getTotalStats().toString()); //logger.info("close expired and idle for over "+HttpIdelTimeout+"ms connection"); }
}, HttpMonitorInterval, HttpMonitorInterval, TimeUnit.MILLISECONDS); } } } return httpClient; }
/** * 构建httpclient实例 * @return * @throws KeyStoreException * @throws NoSuchAlgorithmException * @throws KeyManagementException */ private static CloseableHttpClient createHttpClient() throws NoSuchAlgorithmException, KeyStoreException, KeyManagementException {
SSLContextBuilder builder = new SSLContextBuilder(); // 全部信任 不做身份鉴定 builder.loadTrustMaterial(null, new TrustStrategy() { @Override public boolean isTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException { returntrue; } });
ConnectionSocketFactory plainSocketFactory = null; LayeredConnectionSocketFactory sslSocketFactory = null;
/** * 如果需要进行Sock5代理访问开放如下代码 * */ if(needProxy && SOCKS.endsWith(proxyType)){
plainSocketFactory = new MyConnectionSocketFactory(); sslSocketFactory = new MySSLConnectionSocketFactory(builder.build());
}else {
plainSocketFactory = PlainConnectionSocketFactory.getSocketFactory(); sslSocketFactory = new SSLConnectionSocketFactory(builder.build(), NoopHostnameVerifier.INSTANCE);
}
Registry<ConnectionSocketFactory> registry = RegistryBuilder .<ConnectionSocketFactory> create() .register("http", plainSocketFactory) .register("https", sslSocketFactory).build();
manager = new PoolingHttpClientConnectionManager(registry); // 设置连接参数 manager.setMaxTotal(MAX_CONN); // 最大连接数 manager.setDefaultMaxPerRoute(Max_PRE_ROUTE); // 路由最大连接数
// 请求失败时,进行请求重试 HttpRequestRetryHandler handler = new HttpRequestRetryHandler() {
@Override public boolean retryRequest(IOException e, int i, HttpContext httpContext) {
if (i > 3) { // 重试超过3次,放弃请求 logger.error("retry has more than 3 time, give up request"); returnfalse; } if (e instanceof NoHttpResponseException) { // 服务器没有响应,可能是服务器断开了连接,应该重试 logger.error("receive no response from server, retry"); returntrue; } if (e instanceof SSLHandshakeException) { // SSL握手异常 logger.error("SSL hand shake exception"); returnfalse; } if (e instanceof InterruptedIOException) { // 超时 logger.error("InterruptedIOException"); returnfalse; } if (e instanceof UnknownHostException) { // 服务器不可达 logger.error("server host unknown"); returnfalse; } if (e instanceof ConnectTimeoutException) { // 连接超时 logger.error("Connection Time out"); returnfalse; } if (e instanceof SSLException) { logger.error("SSLException"); returnfalse; }
HttpClientContext context = HttpClientContext.adapt(httpContext); HttpRequest request = context.getRequest();
if (!(request instanceof HttpEntityEnclosingRequest)) { // 如果请求不是关闭连接的请求 returntrue; } returnfalse; } };
CloseableHttpClient client = null; /** * 如果需要进行HTTPS代理访问开放如下代码 * */ if(needProxy && HTTP.endsWith(proxyType)){
client = HttpClients.custom() .setConnectionManager(manager) .setProxy(new HttpHost(proxyHost, proxyPort)) .setRetryHandler(handler).build();
}else {
client = HttpClients.custom() .setConnectionManager(manager) .setRetryHandler(handler).build();
}
return client; }
public static String get(String url) { return get(url, null); }
public static String get(String url,Map<String,Object> headerParams) {
HttpGet httpGet = new HttpGet(url); httpGet.setHeader("User-Agent",USER_AGENT); httpGet.setConfig(requestConfig);
if(headerParams != null && headerParams.size()>0){ for(String headerName : headerParams.keySet()) { httpGet.setHeader(headerName,headerParams.get(headerName)+""); } }
CloseableHttpResponse response = null; InputStream in = null;
String result = null;
try {
HttpClientContext ctx = createContext(); response = getHttpClient().execute(httpGet,ctx);
HttpEntity entity = response.getEntity(); if (entity != null) { in = entity.getContent(); result = IOUtils.toString(in, "utf-8"); }
} catch (Exception e) { logger.error("error",e); } finally { try { if (in != null) in.close(); } catch (IOException e) { logger.error("error",e); }
try { if (response != null) response.close(); } catch (IOException e) { logger.error("error",e); } }
return result; }
public static String postJson(String url,Map<String,Object> requestParams) { return postJson(url, JsonUtil.toJSONString(requestParams)); }
public static String postJson(String url,Map<String,Object> requestParams,Map<String,String> headerParams) { return postJson(url, JsonUtil.toJSONString(requestParams),headerParams); }
public static String postJson(String url,String requestParamStr) { return postJson(url, requestParamStr, null); }
/** * PUT方式调用http请求方法 * @param url * @param requestParamStr * @param headerParams * @return */ public static String put(String url,String requestParamStr,Map<String,String> headerParams) {
HttpPut httpput = new HttpPut(url); httpput.setHeader("Content-Type", APPLICATION_JSON+";charset=" + CharEncoding.UTF_8); httpput.setHeader("Accept",APPLICATION_JSON+";charset=" +CharEncoding.UTF_8); httpput.setHeader("User-Agent",USER_AGENT);
if(headerParams != null && headerParams.size()>0){ for(String headerName : headerParams.keySet()) { httpput.setHeader(headerName,headerParams.get(headerName)+""); } }
StringEntity se = new StringEntity(requestParamStr,CharEncoding.UTF_8); se.setContentType(APPLICATION_JSON+";charset=" +CharEncoding.UTF_8); httpput.setEntity(se); httpput.setConfig(requestConfig);
CloseableHttpResponse response = null; InputStream in = null;
String result = null;
try {
HttpClientContext ctx = createContext(); response = getHttpClient().execute(httpput,ctx);
HttpEntity entity = response.getEntity(); if (entity != null) { in = entity.getContent(); result = IOUtils.toString(in, "utf-8"); }
} catch (Exception e) { logger.error("error",e); } finally { try { if (in != null) in.close(); } catch (IOException e) { logger.error("error",e); }
try { if (response != null) response.close(); } catch (IOException e) { logger.error("error",e); } }
return result;
}
/** * 创建一个HttpClientContext * @return * @throws MalformedChallengeException */ public static HttpClientContext createContext() throws MalformedChallengeException{
HttpClientContext ctx = HttpClientContext.create();
/** * 如果需要进行Sock5代理访问 */ if(needProxy && SOCKS.endsWith(proxyType)){ InetSocketAddress socksaddr = new InetSocketAddress(proxyHost,proxyPort); ctx.setAttribute("socks.address", socksaddr); }else{
/** * 如果需要进行HTTPS代理访问开放如下代码 */ if(needProxy && HTTP.endsWith(proxyType)){
/** * 代理连接认证如果需要认证账号和密码时处理 */ if(needLogin){
AuthState authState = new AuthState(); BasicScheme basicScheme = new BasicScheme(); basicScheme.processChallenge(new BasicHeader(AUTH.PROXY_AUTH, "BASIC realm=default")); authState.update(basicScheme, new UsernamePasswordCredentials(proxyUsername, proxyPassword)); ctx.setAttribute(HttpClientContext.PROXY_AUTH_STATE, authState);
}
}
} return ctx; }
public static String postJson(String url,String requestParamStr,Map<String,String> headerParams) {
HttpPost httppost = new HttpPost(url);
httppost.setHeader("Content-Type", APPLICATION_JSON+";charset=" + CharEncoding.UTF_8); httppost.setHeader("Accept",APPLICATION_JSON+";charset=" +CharEncoding.UTF_8); httppost.setHeader("User-Agent",USER_AGENT);
if(headerParams != null && headerParams.size()>0){ for(String headerName : headerParams.keySet()) { httppost.setHeader(headerName,headerParams.get(headerName)+""); } }
StringEntity se = new StringEntity(requestParamStr,CharEncoding.UTF_8); se.setContentType(APPLICATION_JSON+";charset=" +CharEncoding.UTF_8); httppost.setEntity(se);
httppost.setConfig(requestConfig);
CloseableHttpResponse response = null; InputStream in = null;
String result = null;
try {
HttpClientContext ctx = createContext(); response = getHttpClient().execute(httppost,ctx);
HttpEntity entity = response.getEntity(); if (entity != null) { in = entity.getContent(); result = IOUtils.toString(in, "utf-8"); }
} catch (Exception e) { logger.error("error",e); } finally { try { if (in != null) in.close(); } catch (IOException e) { logger.error("error",e); }
try { if (response != null) response.close(); } catch (IOException e) { logger.error("error",e); } }
return result; }
//requestParamStr---------->>> name=test&age=12 public static String postFormUrlencoded(String url,String requestParamStr) { return postFormUrlencoded(url, requestParamStr ,null);
}
public static String postFormUrlencoded(String url,String requestParamStr,Map<String,Object> headerParams) { Map<String,String> requestParams = new HashMap<String,String>();
String[] strs = requestParamStr.split("&"); for(String str : strs) { String[] keyValues = str.split("="); if(keyValues.length == 2) { requestParams.put(keyValues[0], keyValues[1]); } }
return postFormUrlencoded(url, requestParams,headerParams);
}
public static String postFormUrlencoded(String url,Map<String,String> requestParams) { return postFormUrlencoded(url,requestParams,null); }
public static String postFormUrlencoded(String url,Map<String,String> requestParams,Map<String,Object> headerParams) {
HttpPost httppost = new HttpPost(url);
//application/json httppost.setHeader("Content-Type", APPLICATION_FORM_URLENCODED+";charset=" + CharEncoding.UTF_8); httppost.setHeader("Accept",APPLICATION_JSON+";charset=" +CharEncoding.UTF_8); httppost.setHeader("User-Agent",USER_AGENT);
if(headerParams != null && headerParams.size()>0){ for(String headerName : headerParams.keySet()) { httppost.setHeader(headerName,headerParams.get(headerName)+""); } }
List<NameValuePair> formparams = new ArrayList<NameValuePair>();
for(String keyStr : requestParams.keySet()) { formparams.add(new BasicNameValuePair(keyStr, requestParams.get(keyStr))); }
UrlEncodedFormEntity uefe = new UrlEncodedFormEntity(formparams, Consts.UTF_8); httppost.setEntity(uefe);
httppost.setConfig(requestConfig);
CloseableHttpResponse response = null; InputStream in = null;
String result = null;
try {
HttpClientContext ctx = createContext(); response = getHttpClient().execute(httppost,ctx);
HttpEntity entity = response.getEntity(); if (entity != null) { in = entity.getContent(); result = IOUtils.toString(in, "utf-8"); }
} catch (Exception e) { logger.error("error",e); } finally { try { if (in != null) in.close(); } catch (IOException e) { logger.error("error",e); }
try { if (response != null) response.close(); } catch (IOException e) { logger.error("error",e); } }
return result;
}
//文件上传的通用方法例子测试, 除了file部分参数外,写死了格外的字段参数如scene,output,后台将接收到file,scene,output三个参数,可以根据需求修改 public static String postFormMultipart(String url,InputStream fin,String originalFilename) {
HttpPost httppost = new HttpPost(url);
httppost.setConfig(requestConfig); InputStreamBody bin = new InputStreamBody(fin, originalFilename);
MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create(); multipartEntityBuilder.addPart("file",bin); multipartEntityBuilder.addPart("fileName",new StringBody(originalFilename,ContentType.TEXT_PLAIN)); multipartEntityBuilder.addPart("fileSize",new StringBody("1024",ContentType.TEXT_PLAIN)); multipartEntityBuilder.addPart("scene", new StringBody("default",ContentType.TEXT_PLAIN)); multipartEntityBuilder.addPart("output", new StringBody("json2",ContentType.TEXT_PLAIN)); HttpEntity reqEntity = multipartEntityBuilder.build();
httppost.setEntity(reqEntity);
CloseableHttpResponse response = null; InputStream in = null; String result = null; try {
HttpClientContext ctx = createContext(); response = getHttpClient().execute(httppost,ctx);
HttpEntity entity = response.getEntity(); if (entity != null) { in = entity.getContent(); result = IOUtils.toString(in, "utf-8"); }
} catch (Exception e) { logger.error("error",e); } finally { try { if (in != null) in.close(); } catch (IOException e) { logger.error("error",e); }
try { if (response != null) response.close(); } catch (IOException e) { logger.error("error",e); } }
return result;
}
/** * 下载文件到本地 * @param downloadUrl * @param savePathAndName */ public static void downloadFile(String downloadUrl,String savePathAndName){ HttpGet httpGet = new HttpGet(downloadUrl); httpGet.setHeader("User-Agent",USER_AGENT); httpGet.setConfig(requestConfig);
CloseableHttpResponse response = null; InputStream in = null;
try {
response = getHttpClient().execute(httpGet,HttpClientContext.create());
HttpEntity entity = response.getEntity(); if (entity != null) { in = entity.getContent();
//如果path传进来是/结束的话处理一下,先去掉。 FileOutputStream out = new FileOutputStream(new File(savePathAndName)); IOUtils.copy(in, out); out.close();
}
} catch (IOException e) { logger.error("error",e); } finally { try { if (in != null) in.close(); } catch (IOException e) { logger.error("error",e); }
try { if (response != null) response.close(); } catch (IOException e) { logger.error("error",e); } } }
/** * 下载文件到本地 * @param downloadUrl * @param saveFileName * @param savePath */ public static void downloadFile(String downloadUrl,String saveFileName,String savePath){
//如果path传进来是/结束的话处理一下,先去掉。 String savePathAndName = savePath.endsWith("/") ? savePath.substring(0,savePath.lastIndexOf("/")) : savePath; downloadFile(downloadUrl, savePathAndName);
}
/** * 关闭连接池 */ public static void closeConnectionPool() {
if(manager != null) manager.close(); if(monitorExecutor != null) monitorExecutor.shutdown(); try {if(httpClient != null) httpClient.close();} catch (IOException e) {logger.error("error",e);}
manager = null; monitorExecutor = null; httpClient = null;
}
privatestaticclass MyConnectionSocketFactory extends PlainConnectionSocketFactory {
@Override public Socket createSocket(final HttpContext context) throws IOException { InetSocketAddress socksaddr = (InetSocketAddress) context.getAttribute("socks.address"); Proxy proxy = new Proxy(Proxy.Type.SOCKS, socksaddr); returnnew Socket(proxy); }
@Override public Socket connectSocket(int connectTimeout, Socket socket, HttpHost host, InetSocketAddress remoteAddress, InetSocketAddress localAddress, HttpContext context) throws IOException { // Convert address to unresolved InetSocketAddress unresolvedRemote = InetSocketAddress .createUnresolved(host.getHostName(), remoteAddress.getPort()); returnsuper.connectSocket(connectTimeout, socket, host, unresolvedRemote, localAddress, context); }
}
privatestaticclass MySSLConnectionSocketFactory extends SSLConnectionSocketFactory {
public MySSLConnectionSocketFactory(final SSLContext sslContext) { // You may need this verifier if target site's certificate is not secure super(sslContext, NoopHostnameVerifier.INSTANCE);
}
@Override public Socket createSocket(final HttpContext context) throws IOException { InetSocketAddress socksaddr = (InetSocketAddress) context.getAttribute("socks.address"); Proxy proxy = new Proxy(Proxy.Type.SOCKS, socksaddr); returnnew Socket(proxy); }
@Override public Socket connectSocket(int connectTimeout, Socket socket, HttpHost host, InetSocketAddress remoteAddress, InetSocketAddress localAddress, HttpContext context) throws IOException { // Convert address to unresolved InetSocketAddress unresolvedRemote = InetSocketAddress .createUnresolved(host.getHostName(), remoteAddress.getPort()); returnsuper.connectSocket(connectTimeout, socket, host, unresolvedRemote, localAddress, context); }
}
public static void main(String[] args) throws InterruptedException, MalformedURLException {
String url = "https://api.openai.com/v1/chat/completions"; url = "https://www.baidu.com"; System.out.println(HttpsKitWithProxyAuth.get(url));
//关闭连接池,正式环境中这个不要关闭 HttpsKitWithProxyAuth.closeConnectionPool();
}
} package com.ruoyi.web.controller.meetingminutes.utils;
/** * @Author 不要有情绪的 ljy * @Date 2024/10/31 20:35 * @Description: */
import java.io.IOException; import java.text.SimpleDateFormat; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.util.List; import java.util.Map; import java.util.TimeZone;
import org.slf4j.Logger; import org.slf4j.LoggerFactory;
import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.PropertyAccessor; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.JavaType; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateDeserializer; import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer; import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateSerializer; import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
//https://www.cnblogs.com/christopherchan/p/11071098.html publicclass JsonUtil {
privatefinalstatic Logger logger = LoggerFactory.getLogger(JsonUtil.class);
//日期格式化 privatestaticfinal String STANDARD_FORMAT = "yyyy-MM-dd HH:mm:ss";
privatestatic ObjectMapper objectMapper;
static{
/** * ObjectobjectMapper是JSON操作的核心,Jackson的所有JSON操作都是在ObjectobjectMapper中实现。 * ObjectobjectMapper有多个JSON序列化的方法,可以把JSON字符串保存File、OutputStream等不同的介质中。 * writeValue(File arg0, Object arg1)把arg1转成json序列,并保存到arg0文件中。 * writeValue(OutputStream arg0, Object arg1)把arg1转成json序列,并保存到arg0输出流中。 * writeValueAsBytes(Object arg0)把arg0转成json序列,并把结果输出成字节数组。 * writeValueAsString(Object arg0)把arg0转成json序列,并把结果输出成字符串。 */ objectMapper = new ObjectMapper();
//对象的所有字段全部列入 objectMapper.setSerializationInclusion(JsonInclude.Include.ALWAYS);
//取消默认转换timestamps形式 objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS,false);
//忽略空Bean转json的错误 objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS,false);
//所有的日期格式都统一为以下的样式,即yyyy-MM-dd HH:mm:ss objectMapper.setDateFormat(new SimpleDateFormat(STANDARD_FORMAT));
//忽略 在json字符串中存在,但是在java对象中不存在对应属性的情况。防止错误 objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES,false);
objectMapper.setTimeZone(TimeZone.getTimeZone("GMT+8")); objectMapper.setVisibility(PropertyAccessor.ALL, Visibility.ANY);
//开启美化功能 //objectMapper.enable(SerializationFeature.INDENT_OUTPUT);
//解决Java8 LocalDate,LocalDateTime等序列化问题 JavaTimeModule module=new JavaTimeModule(); module.addSerializer(LocalDateTime.class,new LocalDateTimeSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))); module.addDeserializer(LocalDateTime.class,new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))); module.addSerializer(LocalDate.class,new LocalDateSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd"))); module.addDeserializer(LocalDate.class,new LocalDateDeserializer(DateTimeFormatter.ofPattern("yyyy-MM-dd"))); objectMapper.registerModule(module);
}
/** * 对象转Json格式字符串 * @param obj 对象 * @return Json格式字符串 */ public static String toJSONString(Object o) {
if (o == null) { returnnull; }
if (o instanceof String) return (String) o;
String jsonValue = null; try { jsonValue = objectMapper.writeValueAsString(o); } catch (JsonProcessingException e) { logger.error("Parse Object to String error",e); }
return jsonValue;
}
@SuppressWarnings("unchecked") public static Map<String,Object> castToObject(String fromValue){ if(fromValue == null || "".equals(fromValue) ){ returnnull; }
try { return objectMapper.readValue(fromValue, Map.class); } catch (Exception e) { logger.error("Parse String to Object error:", e); returnnull; }
}
/** * 字符串转换为自定义对象 * @param str 要转换的字符串 * @param clazz 自定义对象的class对象 * @return 自定义对象 */ @SuppressWarnings("unchecked") publicstatic <T> T castToObject(String fromValue, Class<T> clazz){ if(fromValue == null || "".equals(fromValue) || clazz == null){ returnnull; }
try { return clazz.equals(String.class) ? (T) fromValue : objectMapper.readValue(fromValue, clazz); } catch (Exception e) { logger.error("Parse String to Object error:", e); returnnull; }
}
@SuppressWarnings("unchecked") publicstatic <T> T castToObject(String fromValue, TypeReference<T> typeReference) { if (fromValue == null || "".equals(fromValue) || typeReference == null) { returnnull; } try { return (T) (typeReference.getType().equals(String.class) ? fromValue : objectMapper.readValue(fromValue, typeReference)); } catch (IOException e) { logger.error("Parse String to Object error:", e); returnnull; } }
publicstatic <T> T castToObject(String fromValue, Class<?> collectionClazz, Class<?>... elementClazzes) { JavaType javaType = objectMapper.getTypeFactory().constructParametricType(collectionClazz, elementClazzes); try { return objectMapper.readValue(fromValue, javaType); } catch (IOException e) { logger.error("Parse String to Object error : ", e.getMessage()); returnnull; } }
publicstatic <T> T getValue(String fromValue, Class<T> clazz){ return castToObject(fromValue,clazz); }
publicstatic <T> T getValue(String fromValue, TypeReference<T> toValueTypeRef){ return castToObject(fromValue, toValueTypeRef); }
publicstatic <T> T getValue(String fromValue, Class<?> collectionClazz, Class<?>... elementClazzes){ return castToObject(fromValue, collectionClazz, elementClazzes); }
//可通过点语法获取数据,如getValue("data.list","xxxxxxxx",List.class); publicstatic <T> T getValue(String key, String fromValue, Class<T> clazz){ Map<String,Object> infoMap = castToObject(fromValue); if(infoMap == null) returnnull;
return getValue(key, infoMap, clazz); }
//可通过点语法获取数据,如getValue("data.list","xxxxxxxx",new TypeReference<List<User>>(){}); publicstatic <T> T getValue(String key, String fromValue, TypeReference<T> toValueTypeRef){ Map<String,Object> infoMap = castToObject(fromValue); if(infoMap == null) returnnull;
return getValue(key, infoMap, toValueTypeRef); }
publicstatic <T> T getValue(String key, String fromValue, Class<?> collectionClazz, Class<?>... elementClazzes){ Map<String,Object> infoMap = castToObject(fromValue); if(infoMap == null) returnnull; return getValue(key, infoMap, collectionClazz, elementClazzes); }
//可通过点语法获取数据,如getValue("data.list",new TypeReference<List<User>>(){}); @SuppressWarnings("rawtypes") publicstatic <T> T getValue(String key, Map fromMap, Class<T> clazz){
try {
// 首先将key进行拆分 String[] keys = key.split("[.]");
for (int i = 0; i < keys.length; i++) {
Object value = fromMap.get(keys[i]); if(value == null) returnnull;
if (i < keys.length - 1) { fromMap = (Map) value; }else { return objectMapper.convertValue(value, clazz); } }
} catch (Exception e) { logger.error("getValue error : ", e.getMessage()); returnnull; }
returnnull;
}
@SuppressWarnings("rawtypes") publicstatic <T> T getValue(String key, Map fromMap, Class<?> collectionClazz, Class<?>... elementClazzes){ try {
// 首先将key进行拆分 String[] keys = key.split("[.]");
for (int i = 0; i < keys.length; i++) {
Object value = fromMap.get(keys[i]); if(value == null) returnnull;
if (i < keys.length - 1) { fromMap = (Map) value; }else { JavaType javaType = objectMapper.getTypeFactory().constructParametricType(collectionClazz, elementClazzes); return objectMapper.convertValue(value, javaType); }
}
} catch (Exception e) { logger.error("getValue error : ", e.getMessage()); returnnull; }
returnnull; }
@SuppressWarnings("rawtypes") publicstatic <T> T getValue(String key, Map fromMap, TypeReference<T> toValueTypeRef){
try {
// 首先将key进行拆分 String[] keys = key.split("[.]");
for (int i = 0; i < keys.length; i++) {
Object value = fromMap.get(keys[i]); if(value == null) returnnull;
if (i < keys.length - 1) { fromMap = (Map) value; }else { return objectMapper.convertValue(value, toValueTypeRef); }
}
} catch (Exception e) { logger.error("getValue error : ", e.getMessage()); returnnull; }
returnnull;
}
/** * 将对像转换成具体的其他Bean对像 * @param fromValue * @param toValueTypeRef * @return */ publicstatic <T> T convertValue(Object fromValue, TypeReference<T> toValueTypeRef){
try { return objectMapper.convertValue(fromValue, toValueTypeRef); } catch (Exception e) { logger.error("convertValue error : ", e.getMessage()); returnnull; }
}
publicstatic <T> T convertValue(Object fromValue, Class<T> toValueType){
try { return objectMapper.convertValue(fromValue, toValueType); } catch (Exception e) { logger.error("convertValue error : ", e.getMessage()); returnnull; }
}
public static String getString(Map<String,Object> fromMap, String fieldName){ return fromMap.get(fieldName)==null ? null : fromMap.get(fieldName).toString(); }
//根据filedName的key查找map为空时,使用对应的defaultValue默认值替换返回 public static String getString(Map<String,Object> jsonObject, String fieldName,String defaultValue){ return jsonObject.get(fieldName)==null ? defaultValue : jsonObject.get(fieldName).toString(); }
public static Integer getInteger(Map<String,Object> jsonObject, String fieldName){ return jsonObject.get(fieldName)==null ? null : (Integer)jsonObject.get(fieldName); }
public static Double getDouble(Map<String,Object> jsonObject, String fieldName){ return jsonObject.get(fieldName)==null ? null : (Double)jsonObject.get(fieldName); }
public static Boolean getBoolean(Map<String,Object> jsonObject, String fieldName){ return jsonObject.get(fieldName)==null ? false : (Boolean)jsonObject.get(fieldName); }
public static Long getLong(Map<String,Object> jsonObject, String fieldName){ return jsonObject.get(fieldName)==null ? null : (Long)jsonObject.get(fieldName); }
publicstatic <T> List<T> getList(Map<String,Object> jsonObject, String fieldName,Class<T> clazz){ return jsonObject.get(fieldName)==null ? null : JsonUtil.getValue(fieldName, jsonObject, List.class,clazz); }
}`
|