java访问Https服务的客户端示例

关于证书

1、每个人都可以使用一些证书生成工具为自己的https站点生成证书(比如JDK的keytool),大家称它为“自签名证书”,但是自己生成的证书是不被浏览器承认的,所以浏览器会报安全提示,要求你手动安装证书,提示风险,是否继续等。只有通过权威的CA机构付费获得的证书才能被浏览器承认。

2、证书(无客户端服务端之分)保存着IP信息、证书过期时间、证书所有者地址信息等。

双向认证

1、先决条件是有两个或两个以上的证书,一个是服务端证书,另一个或多个是客户端证书。

2、服务端保存着客户端的证书并信任该证书,客户端保存着服务端的证书并信任该证书。这样,在证书验证成功的情况下即可完成请求响应。

3、双向认证安全性更高。

单向认证

1、客户端保存着服务端的证书并信任该证书即可。

2、https一般是单向认证,这样可以让绝大部分人可以访问你的站点。

使用示例代码:

1public interface PCIHttpClient { 2 3 /** 请求头信息:Content-Type **/ 4 public static final String CONTENT_TYPE = "Content-Type"; 5 /** 请求头信息:User-Agent **/ 6 public static final String USER_AGENT = "User-Agent"; 7 /** 默认的内容类型 **/ 8 public static final String DEFAULT_CONTENTTYPE = "application/x-www-form-urlencoded;charset=UTF-8"; 9 /** 默认的用户代理(浏览器类型) **/ 10 public static final String DEFAULT_USERAGENT = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0; SLCC1; .NET CLR 2.0.50727; .NET CLR 3.0.04506; InfoPath.1; .NET CLR 1.1.4322; CIBA)"; 11 /** 默认的读取超时时间(单位毫秒) **/ 12 public static final int DEFAULT_TIMEOUT = 180000; 13 /** 默认的连接超时时间(单位毫秒) **/ 14 public static final int DEFAULT_CONNECTION_TIMEOUT = 60000; 15 16 /** 17 * 发送GET方式请求数据,并接收响应数据 18 * 19 * @param url 请求地址 20 * @param timeout 超时时间(单位毫秒) 21 * @return 响应内容(字符串) 22 * @throws IOException 23 */ 24 public String sendGetAndResponseAsString(String url, 25 int timeout) throws IOException; 26 27 /** 28 * 发送GET方式请求数据,并接收响应数据 29 * 30 * @param url 请求地址 31 * @param headers 请求头信息 32 * @param timeout 超时时间(单位毫秒) 33 * @return 响应内容(字符串) 34 * @throws IOException 35 */ 36 public String sendGetAndResponseAsString(String url, 37 Map<String, String> headers, int timeout) throws IOException; 38 39 /** 40 * 发送GET方式请求数据,并接收响应数据 41 * 42 * @param url 请求地址 43 * @param headers 请求头信息 44 * @param params 请求参数 45 * @param charsetName 字符编码 46 * @param timeout 超时时间(单位毫秒) 47 * @return 响应内容(字符串) 48 * @throws IOException 49 */ 50 public String sendGetAndResponseAsString(String url, 51 Map<String, String> headers, Map<String, String> params, 52 String charsetName, int timeout) throws IOException; 53 54 /** 55 * 发送GET方式请求数据,并接收响应数据 56 * 57 * @param url 请求地址 58 * @param timeout 超时时间(单位毫秒) 59 * @return 响应内容(字节数组) 60 * @throws IOException 61 */ 62 public byte[] sendGetAndResponseAsByteArray(String url, 63 int timeout) throws IOException; 64 65 /** 66 * 发送GET方式请求数据,并接收响应数据 67 * 68 * @param url 请求地址 69 * @param headers 请求头信息 70 * @param timeout 超时时间(单位毫秒) 71 * @return 响应内容(字节数组) 72 * @throws IOException 73 */ 74 public byte[] sendGetAndResponseAsByteArray(String url, 75 Map<String, String> headers, int timeout) throws IOException; 76 77 /** 78 * 发送GET方式请求数据,并接收响应数据 79 * 80 * @param url 请求地址 81 * @param headers 请求头信息 82 * @param params 请求参数 83 * @param charsetName 字符编码 84 * @param timeout 超时时间(单位毫秒) 85 * @return 响应内容(字节数组) 86 * @throws IOException 87 */ 88 public byte[] sendGetAndResponseAsByteArray(String url, 89 Map<String, String> headers, Map<String, String> params, 90 String charsetName, int timeout) throws IOException; 91 92 /** 93 * 发送GET方式请求数据,并接收响应数据 94 * 95 * @param url 请求地址 96 * @param headers 请求头信息 97 * @param params 请求参数 98 * @param charsetName 字符编码 99 * @param timeout 超时时间(单位毫秒) 100 * @return 响应内容(输入流) 101 * @throws IOException 102 */ 103 public InputStream sendGetAndResponseAsStream(String url, 104 Map<String, String> headers, Map<String, String> params, 105 String charsetName, int timeout) throws IOException; 106 107 /** 108 * 发送GET方式请求 109 * 110 * @param url 请求地址 111 * @param headers 请求头信息 112 * @param params 请求参数 113 * @param charsetName 字符编码 114 * @param timeout 超时时间(单位毫秒) 115 * @param output 响应内容(输出流) 116 * @throws IOException 117 */ 118 public void sendGet(String url, Map<String, String> headers, 119 Map<String, String> params, String charsetName, int timeout, 120 OutputStream output) throws IOException; 121 122 /** 123 * 发送POST方式请求数据,并接收响应数据 124 * 125 * @param url 请求地址 126 * @param params 请求参数 127 * @param charsetName 字符编码 128 * @param timeout 超时时间(单位毫秒) 129 * @return 响应内容(字符串) 130 * @throws IOException 131 */ 132 public String sendPostAndResponseAsString(String url, 133 Map<String, String> params, String charsetName, int timeout) throws IOException; 134 135 /** 136 * 发送POST方式请求数据,并接收响应数据 137 * 138 * @param url 请求地址 139 * @param headers 请求头信息 140 * @param params 请求参数 141 * @param timeout 超时时间(单位毫秒) 142 * @param charsetName 字符编码 143 * @return 响应内容(字符串) 144 * @throws IOException 145 */ 146 public String sendPostAndResponseAsString(String url, 147 Map<String, String> headers, Map<String, String> params, 148 int timeout, String charsetName) throws IOException; 149 150 /** 151 * 发送POST方式请求数据,并接收响应数据 152 * 153 * @param url 请求地址 154 * @param headers 请求头信息 155 * @param stringOrStream 请求体内容(字符串或者输入流) 156 * @param charsetName 字符编码 157 * @param timeout 超时时间(单位毫秒) 158 * @return 响应内容(字符串) 159 * @throws IOException 160 */ 161 public String sendPostAndResponseAsString(String url, 162 Map<String, String> headers, Object stringOrStream, 163 String charsetName, int timeout) throws IOException; 164 165 /** 166 * 发送POST方式请求数据,并接收响应数据 167 * 168 * @param url 请求地址 169 * @param headers 请求头信息 170 * @param params 请求参数 171 * @param stringOrStream 请求体内容(字符串或者输入流) 172 * @param charsetName 字符编码 173 * @param timeout 超时时间(单位毫秒) 174 * @return 响应内容(字符串) 175 * @throws IOException 176 */ 177 public String sendPostAndResponseAsString(String url, 178 Map<String, String> headers, Map<String, String> params, 179 Object stringOrStream, String charsetName, int timeout) throws IOException; 180 181 /** 182 * 发送POST方式请求数据,并接收响应数据 183 * 184 * @param url 请求地址 185 * @param params 请求参数 186 * @param charsetName 字符编码 187 * @param timeout 超时时间(单位毫秒) 188 * @return 响应内容(字节数组) 189 * @throws IOException 190 */ 191 public byte[] sendPostAndResponseAsByteArray(String url, 192 Map<String, String> params, String charsetName, int timeout) throws IOException; 193 194 /** 195 * 发送POST方式请求数据,并接收响应数据 196 * 197 * @param url 请求地址 198 * @param headers 请求头信息 199 * @param params 请求参数 200 * @param timeout 超时时间(单位毫秒) 201 * @param charsetName 字符编码 202 * @return 响应内容(字节数组) 203 * @throws IOException 204 */ 205 public byte[] sendPostAndResponseAsByteArray(String url, 206 Map<String, String> headers, Map<String, String> params, 207 int timeout, String charsetName) throws IOException; 208 209 /** 210 * 发送POST方式请求数据,并接收响应数据 211 * 212 * @param url 请求地址 213 * @param headers 请求头信息 214 * @param stringOrStream 请求体内容(字符串或者输入流) 215 * @param charsetName 字符编码 216 * @param timeout 超时时间(单位毫秒) 217 * @return 响应内容(字节数组) 218 * @throws IOException 219 */ 220 public byte[] sendPostAndResponseAsByteArray(String url, 221 Map<String, String> headers, Object stringOrStream, 222 String charsetName, int timeout) throws IOException; 223 224 /** 225 * 发送POST方式请求数据,并接收响应数据 226 * 227 * @param url 请求地址 228 * @param headers 请求头信息 229 * @param params 请求参数 230 * @param stringOrStream 请求体内容(字符串或者输入流) 231 * @param charsetName 字符编码 232 * @param timeout 超时时间(单位毫秒) 233 * @return 响应内容(字节数组) 234 * @throws IOException 235 */ 236 public byte[] sendPostAndResponseAsByteArray(String url, 237 Map<String, String> headers, Map<String, String> params, 238 Object stringOrStream, String charsetName, int timeout) throws IOException; 239 240 /** 241 * 发送POST方式请求数据,并接收响应数据 242 * 243 * @param url 请求地址 244 * @param headers 请求头信息 245 * @param params 请求参数 246 * @param stringOrStream 请求体内容(字符串或者输入流) 247 * @param charsetName 字符编码 248 * @param timeout 超时时间(单位毫秒) 249 * @return 响应内容(输入流) 250 * @throws IOException 251 */ 252 public InputStream sendPostAndResponseAsStream(String url, 253 Map<String, String> headers, Map<String, String> params, 254 Object stringOrStream, String charsetName, int timeout) throws IOException; 255 256 /** 257 * 发送POST方式请求 258 * 259 * @param url 请求地址 260 * @param headers 请求头信息 261 * @param params 请求参数 262 * @param stringOrStream 请求体内容(字符串或者输入流) 263 * @param charsetName 字符编码 264 * @param timeout 超时时间(单位毫秒) 265 * @param output 响应内容(输出流) 266 * @throws IOException 267 */ 268 public void sendPost(String url, Map<String, String> headers, 269 Map<String, String> params, Object stringOrStream, 270 String charsetName, int timeout, OutputStream output) throws IOException; 271 272 /** 273 * 发送GET方式请求 274 * 275 * @param url 请求地址 276 * @param headers 请求头信息 277 * @param params 请求参数 278 * @param charsetName 字符编码 279 * @param timeout 超时时间(单位毫秒) 280 * @return 281 * @throws IOException 282 * 283 * @since 2.0.0 284 */ 285 public PCIHttpResponse sendGet(String url, Map<String, String> headers, 286 Map<String, String> params, String charsetName, int timeout) throws IOException; 287 288 /** 289 * 发送POST方式请求 290 * 291 * @param url 请求地址 292 * @param headers 请求头信息 293 * @param params 请求参数 294 * @param stringOrStream 请求体内容(字符串或者输入流) 295 * @param charsetName 字符编码 296 * @param timeout 超时时间(单位毫秒) 297 * @return 298 * @throws IOException 299 * 300 * @since 2.0.0 301 */ 302 public PCIHttpResponse sendPost(String url, Map<String, String> headers, 303 Map<String, String> params, Object stringOrStream, 304 String charsetName, int timeout) throws IOException; 305 306} 307 308public class CustomConstants { 309 310 /** 字符编码:UTF-8 */ 311 public static final String CHARSET_UTF8 = "UTF-8"; 312 313} 314 315public class CustomStringUtils { 316 317 private static LogUtils logger = new LogUtils(CustomStringUtils.class); 318 319 /** 320 * 长度不足,左补字符 321 * @param str 322 * @param ch 323 * @param len 324 * @return 325 */ 326 public static String leftFill(String str, char ch, int len) { 327 if (str == null) { 328 str = ""; 329 } 330 while (str.length() < len) { 331 str = ch + str; 332 } 333 return str; 334 } 335 336 /** 337 * 长度不足,右补字符 338 * @param str 339 * @param ch 340 * @param len 341 * @return 342 */ 343 public static String rightFill(String str, char ch, int len) { 344 if (str == null) { 345 str = ""; 346 } 347 while (str.length() < len) { 348 str = str + ch; 349 } 350 return str; 351 } 352 353 /** 354 * 拼接字符串 355 * @param objs 356 * @return 357 */ 358 public static String append(Object... objs) { 359 if (objs == null || objs.length == 0) { 360 return ""; 361 } 362 StringBuffer buffer = new StringBuffer(); 363 for (Object obj : objs) { 364 buffer.append(obj); 365 } 366 return buffer.toString(); 367 } 368 369 /** 370 * 如果字符串为空,则返回空字符 371 * @param str 372 * @return 373 */ 374 public static String nullToBlank(String str) { 375 return str == null ? "" : str; 376 } 377 378 /** 379 * 将map转化成字符串 380 * @param map 381 * @return 格式:key1=value1&key2=value2... 382 */ 383 public static String convertMapToString(Map<String, String> map) { 384 if (map == null || map.isEmpty()) { 385 return null; 386 } 387 StringBuffer buffer = new StringBuffer(); 388 boolean first = true; 389 for (Map.Entry<String, String> entry : map.entrySet()) { 390 if (first) { 391 buffer.append(entry.getKey()).append("=").append(entry.getValue()); 392 first = false; 393 } else { 394 buffer.append("&").append(entry.getKey()).append("=").append(entry.getValue()); 395 } 396 } 397 return buffer.toString(); 398 } 399 400 /** 401 * 将map转化成字符串,并对map.value进行URL编码 402 * @param map 403 * @param encoding 404 * @return 格式:key1=value1&key2=value2... 405 */ 406 public static String convertMapToString(Map<String, String> map, String encoding) { 407 if (map == null || map.isEmpty()) { 408 return null; 409 } 410 StringBuffer buffer = new StringBuffer(); 411 boolean first = true; 412 for (Map.Entry<String, String> entry : map.entrySet()) { 413 if (first) { 414 buffer.append(entry.getKey()).append("=").append(urlEncode(entry.getValue(), encoding)); 415 first = false; 416 } else { 417 buffer.append("&").append(entry.getKey()).append("=").append(urlEncode(entry.getValue(), encoding)); 418 } 419 } 420 return buffer.toString(); 421 } 422 423 /** 424 * 将map转化成字符串(当参数值为null时,则忽略该参数) 425 * @param map 426 * @return 格式:key1=value1&key2=value2... 427 */ 428 public static String convertMapToStringIgnoreNull(Map<String, String> map) { 429 if (map == null || map.isEmpty()) { 430 return null; 431 } 432 StringBuffer buffer = new StringBuffer(); 433 boolean first = true; 434 for (Map.Entry<String, String> entry : map.entrySet()) { 435 if (entry.getValue() == null) { 436 continue; 437 } 438 if (first) { 439 buffer.append(entry.getKey()).append("=").append(entry.getValue()); 440 first = false; 441 } else { 442 buffer.append("&").append(entry.getKey()).append("=").append(entry.getValue()); 443 } 444 } 445 return buffer.toString(); 446 } 447 448 /** 449 * 将map转化成字符串,并对map.value进行URL编码(当参数值为null时,则忽略该参数) 450 * @param map 451 * @param encoding 452 * @return 格式:key1=value1&key2=value2... 453 */ 454 public static String convertMapToStringIgnoreNull(Map<String, String> map, String encoding) { 455 if (map == null || map.isEmpty()) { 456 return null; 457 } 458 StringBuffer buffer = new StringBuffer(); 459 boolean first = true; 460 for (Map.Entry<String, String> entry : map.entrySet()) { 461 if (entry.getValue() == null) { 462 continue; 463 } 464 if (first) { 465 buffer.append(entry.getKey()).append("=").append(urlEncode(entry.getValue(), encoding)); 466 first = false; 467 } else { 468 buffer.append("&").append(entry.getKey()).append("=").append(urlEncode(entry.getValue(), encoding)); 469 } 470 } 471 return buffer.toString(); 472 } 473 474 /** 475 * 对字符串进行URL编码 476 * @param str 477 * @param encoding 478 * @return 479 */ 480 public static String urlEncode(String str, String encoding) { 481 if (str == null || "".equals(str)) { 482 return str; 483 } 484 try { 485 return URLEncoder.encode(str, encoding); 486 } catch (UnsupportedEncodingException e) { 487 logger.error(append("URL encode string error. str=", str, ", encoding=", encoding), e); 488 return str; 489 } 490 } 491 492 /** 493 * 对字符串进行URL解码 494 * @param str 495 * @param encoding 496 * @return 497 */ 498 public static String urlDecode(String str, String encoding) { 499 if (str == null || "".equals(str)) { 500 return str; 501 } 502 try { 503 return URLDecoder.decode(str, encoding); 504 } catch (UnsupportedEncodingException e) { 505 logger.error(append("URL decode string error. str=", str, ", encoding=", encoding), e); 506 return str; 507 } 508 } 509 510 /** 511 * 字符串的字节长度是否超出边界值 512 * @param str 字符串 513 * @param bounds 边界值 514 * @param charsetName 字符编码 515 * @return 516 */ 517 public static boolean bytesLengthOutOfBounds( 518 String str, int bounds, String charsetName) { 519 if (bounds < 0 || str == null || "".equals(str)) { 520 return false; 521 } 522 try { 523 int bytesLen = str.getBytes(charsetName).length; 524 return bytesLen > bounds; 525 } catch (UnsupportedEncodingException e) { 526 logger.error(append("Check bytes length out of bounds error. str=", 527 str, ", charsetName=", charsetName), e); 528 } 529 return false; 530 } 531 532 /** 533 * @Title: generate 534 * @Description: 随机生成指定长度的16进制的字符串 535 * @since: 0.0.1 536 * @param len 字符串长度 537 * @return 538 */ 539 public static String generateRandomHex(int len){ 540 541 if (len < 1) { 542 return null; 543 } 544 545 StringBuffer sb = new StringBuffer(); 546 Random random = new Random(); 547 548 for (int i = 0; i < len; i++) { 549 sb.append(Integer.toHexString(random.nextInt(16))); 550 } 551 552 return sb.toString().toUpperCase(); 553 } 554 555 /** 556 * @Title: generateConformOddCheckHex 557 * @Description: 生成符合奇校验的字符串 558 * @since: 0.0.1 559 * @param len 字节长度 560 * @return 561 */ 562 public static String generateConformOddCheckHex(int len) { 563 564 byte[] bytes = new byte[len]; 565 for (int i = 0; i < len; i++) { 566 Random random = new Random(); 567 int randomInt = random.nextInt(255); 568 String binaryString = Integer.toBinaryString(randomInt); 569 boolean oddCheck = isConformOddCheck(binaryString); 570 if (!oddCheck) { 571 randomInt ^= 1; 572 } 573// System.err.println(Integer.toBinaryString(randomInt)); 574 byte b = (byte) randomInt; 575 bytes[i] = b; 576 } 577 String hexString = CommonUtils.byte2hexString(bytes); 578 return hexString; 579 } 580 581 /** 582 * @Title: oddCheck 583 * @Description: 检验是否符合奇校验 584 * @since: 0.0.1 585 * @param binaryString 586 * @return 587 */ 588 private static boolean isConformOddCheck(String binaryString) { 589 int sum = 0; 590 char[] charArray = binaryString.toCharArray(); 591 for(char c : charArray){ 592 if (c == '1') { 593 sum ++; 594 } 595 } 596 if (sum%2 == 1) { 597 return true; 598 } 599 return false; 600 } 601 602} 603 604public class IOUtils { 605 606 private static LogUtils logger = new LogUtils(IOUtils.class); 607 608 /** 默认的缓冲区大小 **/ 609 private static final int DEFAULT_BUFFER_SIZE = 4096; 610 611 /** 612 * 将字节输入流转换成字节数组 613 * @param input 614 * @return 615 * @throws IOException 616 */ 617 public static byte[] toByteArray(InputStream input) throws IOException { 618 ByteArrayOutputStream output = null; 619 try { 620 output = new ByteArrayOutputStream(); 621 copy(input, output); 622 return output.toByteArray(); 623 } finally { 624 closeQuietly(output); 625 } 626 } 627 628 /** 629 * 将字符输入流转换成字节数组 630 * @param reader 631 * @return 632 * @throws IOException 633 */ 634 public static byte[] toByteArray(Reader reader) throws IOException { 635 ByteArrayOutputStream output = null; 636 try { 637 output = new ByteArrayOutputStream(); 638 copy(reader, output); 639 return output.toByteArray(); 640 } finally { 641 closeQuietly(output); 642 } 643 } 644 645 /** 646 * 将字符输入流转换成字节数组 647 * @param reader 648 * @param encoding 649 * @return 650 * @throws IOException 651 */ 652 public static byte[] toByteArray(Reader reader, String encoding) throws IOException { 653 ByteArrayOutputStream output = null; 654 try { 655 output = new ByteArrayOutputStream(); 656 copy(reader, output, encoding); 657 return output.toByteArray(); 658 } finally { 659 closeQuietly(output); 660 } 661 } 662 663 /** 664 * 将字节输入流转换成字符串 665 * @param input 666 * @return 667 * @throws IOException 668 */ 669 public static String toString(InputStream input) throws IOException { 670 StringWriter writer = null; 671 try { 672 writer = new StringWriter(); 673 copy(input, writer); 674 return writer.toString(); 675 } finally { 676 closeQuietly(writer); 677 } 678 } 679 680 /** 681 * 将字节输入流转换成字符串 682 * @param input 683 * @param encoding 684 * @return 685 * @throws IOException 686 */ 687 public static String toString(InputStream input, String encoding) throws IOException { 688 StringWriter writer = null; 689 try { 690 writer = new StringWriter(); 691 copy(input, writer, encoding); 692 return writer.toString(); 693 } finally { 694 closeQuietly(writer); 695 } 696 } 697 698 /** 699 * 将字符输入流转换成字符串 700 * @param reader 701 * @return 702 * @throws IOException 703 */ 704 public static String toString(Reader reader) throws IOException { 705 StringWriter writer = null; 706 try { 707 writer = new StringWriter(); 708 copy(reader, writer); 709 return writer.toString(); 710 } finally { 711 closeQuietly(writer); 712 } 713 } 714 715 /** 716 * 按行读取字节输入流 717 * @param input 718 * @return 719 * @throws IOException 720 */ 721 public static List<String> readLines(InputStream input) throws IOException { 722// InputStreamReader reader = new InputStreamReader(input); 723// return readLines(reader); 724 InputStreamReader reader = null; 725 try { 726 reader = new InputStreamReader(input); 727 return readLines(reader); 728 } finally { 729 closeQuietly(reader); 730 } 731 } 732 733 /** 734 * 按行读取字节输入流 735 * @param input 736 * @param encoding 737 * @return 738 * @throws IOException 739 */ 740 public static List<String> readLines(InputStream input, String encoding) throws IOException { 741// if (encoding == null) { 742// return readLines(input); 743// } 744// InputStreamReader reader = new InputStreamReader(input, encoding); 745// return readLines(reader); 746 if (encoding == null) { 747 return readLines(input); 748 } 749 InputStreamReader reader = null; 750 try { 751 reader = new InputStreamReader(input, encoding); 752 return readLines(reader); 753 } finally { 754 closeQuietly(reader); 755 } 756 } 757 758 /** 759 * 按行读取字符输入流 760 * @param reader 761 * @return 762 * @throws IOException 763 */ 764 public static List<String> readLines(Reader reader) throws IOException { 765// BufferedReader br = new BufferedReader(reader); 766// List<String> lines = new ArrayList<String>(); 767// String line = br.readLine(); 768// while (line != null) { 769// lines.add(line); 770// line = br.readLine(); 771// } 772// return lines; 773 BufferedReader br = null; 774 try { 775 br = new BufferedReader(reader); 776 List<String> lines = new ArrayList<String>(); 777 String line = br.readLine(); 778 while (line != null) { 779 lines.add(line); 780 line = br.readLine(); 781 } 782 return lines; 783 } finally { 784 closeQuietly(br); 785 } 786 } 787 788 /** 789 * 阻塞地读取字节输入流 790 * @param input 791 * @param buffer 792 * @param off 793 * @param length 794 * @throws IOException 795 */ 796 public static void read(InputStream input, 797 byte[] buffer, int off, int length) throws IOException { 798 while (off < length) { 799 off = off + input.read(buffer, off, length - off); 800 if (off < 0) { 801 throw new IOException("读取时出错[readLen=" + off + "]"); 802 } 803 } 804 } 805 806 /** 807 * 将字节输入流拷贝到字符输出流 808 * @param input 809 * @param writer 810 * @throws IOException 811 */ 812 public static void copy(InputStream input, Writer writer) throws IOException { 813// InputStreamReader reader = new InputStreamReader(input); 814// copy(reader, writer); 815 InputStreamReader reader = null; 816 try { 817 reader = new InputStreamReader(input); 818 copy(reader, writer); 819 } finally { 820 closeQuietly(reader); 821 } 822 } 823 824 /** 825 * 将字节输入流拷贝到字符输出流 826 * @param input 827 * @param writer 828 * @param encoding 829 * @throws IOException 830 */ 831 public static void copy(InputStream input, Writer writer, String encoding) throws IOException { 832// if (encoding == null) { 833// copy(input, writer); 834// } else { 835// InputStreamReader reader = new InputStreamReader(input, encoding); 836// copy(reader, writer); 837// } 838 if (encoding == null) { 839 copy(input, writer); 840 } else { 841 InputStreamReader reader = null; 842 try { 843 reader = new InputStreamReader(input, encoding); 844 copy(reader, writer); 845 } finally { 846 closeQuietly(reader); 847 } 848 } 849 } 850 851 /** 852 * 将字节输入流拷贝到字节输出流 853 * @param input 854 * @param output 855 * @return 字节数 856 * @throws IOException 857 */ 858 public static int copy(InputStream input, OutputStream output) throws IOException { 859 byte[] buffer = new byte[DEFAULT_BUFFER_SIZE]; 860 int count = 0; 861 int n = 0; 862 while (-1 != (n = input.read(buffer))) { 863 output.write(buffer, 0, n); 864 count += n; 865 } 866 output.flush(); 867 return count; 868 } 869 870 /** 871 * 将字符输入流拷贝到字节输出流 872 * @param reader 873 * @param output 874 * @throws IOException 875 */ 876 public static void copy(Reader reader, OutputStream output) throws IOException { 877// OutputStreamWriter writer = new OutputStreamWriter(output); 878// copy(reader, writer); 879 OutputStreamWriter writer = null; 880 try { 881 writer = new OutputStreamWriter(output); 882 copy(reader, writer); 883 } finally { 884 closeQuietly(writer); 885 } 886 } 887 888 /** 889 * 将字符输入流拷贝到字节输出流 890 * @param reader 891 * @param output 892 * @param encoding 893 * @throws IOException 894 */ 895 public static void copy(Reader reader, OutputStream output, String encoding) 896 throws IOException { 897// if (encoding == null) { 898// copy(reader, output); 899// } else { 900// OutputStreamWriter writer = new OutputStreamWriter(output, encoding); 901// copy(reader, writer); 902// } 903 if (encoding == null) { 904 copy(reader, output); 905 } else { 906 OutputStreamWriter writer = null; 907 try { 908 writer = new OutputStreamWriter(output, encoding); 909 copy(reader, writer); 910 } finally { 911 closeQuietly(writer); 912 } 913 } 914 } 915 916 /** 917 * 将字符输入流拷贝到字符输出流 918 * @param reader 919 * @param writer 920 * @return 字符数 921 * @throws IOException 922 */ 923 public static int copy(Reader reader, Writer writer) throws IOException { 924 char[] buffer = new char[DEFAULT_BUFFER_SIZE]; 925 int count = 0; 926 int n = 0; 927 while (-1 != (n = reader.read(buffer))) { 928 writer.write(buffer, 0, n); 929 count += n; 930 } 931 writer.flush(); 932 return count; 933 } 934 935 /** 936 * 关闭IO流 937 * @param close 938 */ 939 public static void closeQuietly(Closeable close) { 940 closeQuietly(close, "关闭IO流出错!"); 941 } 942 943 /** 944 * 关闭IO流 945 * @param close 946 * @param errorMsg 947 */ 948 public static void closeQuietly(Closeable close, String errorMsg) { 949 if (close != null) { 950 try { 951 close.close(); 952 } catch (IOException e) { 953 logger.error(errorMsg, e); 954 } 955 } 956 } 957 958public class PCIHttpClientImpl4 implements PCIHttpClient { 959 960 private static LogUtils logger = new LogUtils(PCIHttpClientImpl4.class); 961 962 private SSLConnectionSocketFactory sslSocketFactory = null; 963 964 /** 965 * 构造方法 966 * 967 * <p>允许信任任何证书策略和允许任何域名验证</p> 968 */ 969 public PCIHttpClientImpl4() { 970 this(false, false, true, true, null, null, null); 971 } 972 973 /** 974 * 构造方法 975 * 976 * @param allowAnyTrustMaterial 是否允许信任任何证书策略 977 * @param allowAnyHostnameVerifier 是否允许任何域名验证 978 */ 979 public PCIHttpClientImpl4(boolean allowAnyTrustMaterial, boolean allowAnyHostnameVerifier) { 980 this(false, false, allowAnyTrustMaterial, allowAnyHostnameVerifier, null, null, null); 981 } 982 983 /** 984 * 构造方法 985 * 986 * @param loadKeyMaterial 是否加载密钥 987 * @param loadTrustMaterial 是否加载信任证书 988 * @param keystoreFilePath 密钥库文件路径 989 * @param storePassword 密钥库密码 990 * @param keyPassword 私钥密码 991 */ 992 public PCIHttpClientImpl4(boolean loadKeyMaterial, boolean loadTrustMaterial, 993 String keystoreFilePath, String storePassword, String keyPassword) { 994 this(loadKeyMaterial, loadTrustMaterial, false, true, keystoreFilePath, storePassword, keyPassword); 995 } 996 997 /** 998 * 构造方法 999 * 1000 * @param loadKeyMaterial 是否加载密钥 1001 * @param loadTrustMaterial 是否加载信任证书(若allowAnyTrustMaterial=true,则loadTrustMaterial无效) 1002 * @param allowAnyTrustMaterial 是否允许信任任何证书策略 1003 * @param allowAnyHostnameVerifier 是否允许任何域名验证 1004 * @param keystoreFilePath 密钥库文件路径 1005 * @param storePassword 密钥库密码 1006 * @param keyPassword 私钥密码 1007 */ 1008 public PCIHttpClientImpl4(boolean loadKeyMaterial, boolean loadTrustMaterial, 1009 boolean allowAnyTrustMaterial, boolean allowAnyHostnameVerifier, 1010 String keystoreFilePath, String storePassword, String keyPassword) { 1011 try { 1012 // Create SSLContext 1013 SSLContextBuilder sslContextBuilder = new SSLContextBuilder(); 1014 if (loadKeyMaterial) { 1015 sslContextBuilder.loadKeyMaterial( 1016 new File(keystoreFilePath), storePassword.toCharArray(), keyPassword.toCharArray()); 1017 } 1018 if (allowAnyTrustMaterial) { 1019 sslContextBuilder.loadTrustMaterial(null, new AnyTrustStrategy()); 1020 } else if (loadTrustMaterial) { 1021 sslContextBuilder.loadTrustMaterial( 1022 new File(keystoreFilePath), storePassword.toCharArray(), new TrustSelfSignedStrategy()); 1023 } 1024 SSLContext sslContext = sslContextBuilder.build(); 1025 1026 // Create SSLConnectionSocketFactory 1027 if (allowAnyHostnameVerifier) { 1028 sslSocketFactory = new SSLConnectionSocketFactory(sslContext, new AnyHostnameVerifier()); 1029 } else { 1030 sslSocketFactory = new SSLConnectionSocketFactory(sslContext); 1031 } 1032 } catch (NoSuchAlgorithmException e) { 1033 logger.error("Error occurred: NoSuchAlgorithmException", e); 1034 } catch (KeyStoreException e) { 1035 logger.error("Error occurred: KeyStoreException", e); 1036 } catch (UnrecoverableKeyException e) { 1037 logger.error("Error occurred: UnrecoverableKeyException", e); 1038 } catch (CertificateException e) { 1039 logger.error("Error occurred: CertificateException", e); 1040 } catch (IOException e) { 1041 logger.error("Error occurred: IOException", e); 1042 } catch (KeyManagementException e) { 1043 logger.error("Error occurred: KeyManagementException", e); 1044 } 1045 } 1046 1047 /** 1048 * 信任任何证书策略 1049 */ 1050 private static class AnyTrustStrategy implements TrustStrategy { 1051 @Override 1052 public boolean isTrusted(X509Certificate[] chain, String authType) 1053 throws CertificateException { 1054 return true; 1055 } 1056 } 1057 1058 /** 1059 * 允许任何域名验证 1060 */ 1061 private static class AnyHostnameVerifier implements HostnameVerifier { 1062 @Override 1063 public boolean verify(String hostname, SSLSession session) { 1064 return true; 1065 } 1066 } 1067 1068 @Override 1069 public String sendGetAndResponseAsString(String url, 1070 int timeout) throws IOException { 1071 return sendGetAndResponseAsString(url, null, null, CustomConstants.CHARSET_UTF8, timeout); 1072 } 1073 1074 @Override 1075 public String sendGetAndResponseAsString(String url, 1076 Map<String, String> headers, int timeout) throws IOException { 1077 return sendGetAndResponseAsString(url, headers, null, CustomConstants.CHARSET_UTF8, timeout); 1078 } 1079 1080 @Override 1081 public String sendGetAndResponseAsString(String url, 1082 Map<String, String> headers, Map<String, String> params, 1083 String charsetName, int timeout) throws IOException { 1084 byte[] buffer = sendGetAndResponseAsByteArray(url, headers, params, charsetName, timeout); 1085 if (buffer == null) { 1086 return null; 1087 } 1088 return new String(buffer, charsetName); 1089 } 1090 1091 @Override 1092 public byte[] sendGetAndResponseAsByteArray(String url, 1093 int timeout) throws IOException { 1094 return sendGetAndResponseAsByteArray(url, null, null, null, timeout); 1095 } 1096 1097 @Override 1098 public byte[] sendGetAndResponseAsByteArray(String url, 1099 Map<String, String> headers, int timeout) throws IOException { 1100 return sendGetAndResponseAsByteArray(url, headers, null, null, timeout); 1101 } 1102 1103 @Override 1104 public byte[] sendGetAndResponseAsByteArray(String url, 1105 Map<String, String> headers, Map<String, String> params, 1106 String charsetName, int timeout) throws IOException { 1107 ByteArrayOutputStream output = null; 1108 try { 1109 output = new ByteArrayOutputStream(); 1110 sendGet(url, headers, params, charsetName, timeout, output); 1111 return output.toByteArray(); 1112 } finally { 1113 IOUtils.closeQuietly(output); 1114 } 1115 } 1116 1117 @Override 1118 public InputStream sendGetAndResponseAsStream(String url, 1119 Map<String, String> headers, Map<String, String> params, 1120 String charsetName, int timeout) throws IOException { 1121 byte[] buffer = sendGetAndResponseAsByteArray(url, headers, params, charsetName, timeout); 1122 if (buffer == null) { 1123 return null; 1124 } 1125 return new ByteArrayInputStream(buffer); 1126 } 1127 1128 @Override 1129 public void sendGet(String url, Map<String, String> headers, 1130 Map<String, String> params, String charsetName, int timeout, 1131 OutputStream output) throws IOException { 1132 if (StringUtils.isEmpty(url)) { 1133 logger.error("The url can not be null."); 1134 throw new IllegalArgumentException("The url can not be null."); 1135 } 1136 sendAndResponseAsStream(new HttpGet(createURI(url, params, charsetName)), 1137 headers, timeout, output); 1138 } 1139 1140 @Override 1141 public String sendPostAndResponseAsString(String url, 1142 Map<String, String> params, String charsetName, int timeout) throws IOException { 1143 return sendPostAndResponseAsString(url, null, params, null, charsetName, timeout); 1144 } 1145 1146 @Override 1147 public String sendPostAndResponseAsString(String url, 1148 Map<String, String> headers, Map<String, String> params, 1149 int timeout, String charsetName) throws IOException { 1150 return sendPostAndResponseAsString(url, headers, params, null, charsetName, timeout); 1151 } 1152 1153 @Override 1154 public String sendPostAndResponseAsString(String url, 1155 Map<String, String> headers, Object stringOrStream, 1156 String charsetName, int timeout) throws IOException { 1157 return sendPostAndResponseAsString(url, headers, null, stringOrStream, charsetName, timeout); 1158 } 1159 1160 @Override 1161 public String sendPostAndResponseAsString(String url, 1162 Map<String, String> headers, Map<String, String> params, 1163 Object stringOrStream, String charsetName, int timeout) throws IOException { 1164 byte[] buffer = sendPostAndResponseAsByteArray( 1165 url, headers, params, stringOrStream, charsetName, timeout); 1166 if (buffer == null) { 1167 return null; 1168 } 1169 return new String(buffer, charsetName); 1170 } 1171 1172 @Override 1173 public byte[] sendPostAndResponseAsByteArray(String url, 1174 Map<String, String> params, String charsetName, int timeout) throws IOException { 1175 return sendPostAndResponseAsByteArray(url, null, params, null, charsetName, timeout); 1176 } 1177 1178 @Override 1179 public byte[] sendPostAndResponseAsByteArray(String url, 1180 Map<String, String> headers, Map<String, String> params, 1181 int timeout, String charsetName) throws IOException { 1182 return sendPostAndResponseAsByteArray(url, headers, params, null, charsetName, timeout); 1183 } 1184 1185 @Override 1186 public byte[] sendPostAndResponseAsByteArray(String url, 1187 Map<String, String> headers, Object stringOrStream, 1188 String charsetName, int timeout) throws IOException { 1189 return sendPostAndResponseAsByteArray(url, headers, null, stringOrStream, charsetName, timeout); 1190 } 1191 1192 @Override 1193 public byte[] sendPostAndResponseAsByteArray(String url, 1194 Map<String, String> headers, Map<String, String> params, 1195 Object stringOrStream, String charsetName, int timeout) throws IOException { 1196 ByteArrayOutputStream output = null; 1197 try { 1198 output = new ByteArrayOutputStream(); 1199 sendPost(url, headers, params, stringOrStream, charsetName, timeout, output); 1200 return output.toByteArray(); 1201 } finally { 1202 IOUtils.closeQuietly(output); 1203 } 1204 } 1205 1206 @Override 1207 public InputStream sendPostAndResponseAsStream(String url, 1208 Map<String, String> headers, Map<String, String> params, 1209 Object stringOrStream, String charsetName, int timeout) throws IOException { 1210 byte[] buffer = sendPostAndResponseAsByteArray( 1211 url, headers, params, stringOrStream, charsetName, timeout); 1212 if (buffer == null) { 1213 return null; 1214 } 1215 return new ByteArrayInputStream(buffer); 1216 } 1217 1218 @Override 1219 public void sendPost(String url, Map<String, String> headers, 1220 Map<String, String> params, Object stringOrStream, 1221 String charsetName, int timeout, OutputStream output) throws IOException { 1222 if (StringUtils.isEmpty(url)) { 1223 logger.error("The url can not be null."); 1224 throw new IllegalArgumentException("The url can not be null."); 1225 } 1226 1227 // post请求方式 1228 HttpPost method = new HttpPost(createURI(url, params, charsetName)); 1229 1230 // 设置请求头信息 1231 if (headers == null) { 1232 headers = new HashMap<String, String>(); 1233 } 1234 if (!headers.containsKey(CONTENT_TYPE)) { 1235 headers.put(CONTENT_TYPE, DEFAULT_CONTENTTYPE); 1236 } 1237 1238 // 设置请求体内容 1239 if (stringOrStream != null) { 1240 HttpEntity entity = null; 1241 if (stringOrStream instanceof InputStream) { 1242 entity = new InputStreamEntity((InputStream) stringOrStream); 1243 } else { 1244 entity = new StringEntity(stringOrStream.toString(), 1245 ContentType.create(CONTENT_TYPE, charsetName)); 1246 } 1247 method.setEntity(entity); 1248 } 1249 1250 // 发送请求数据,并接收响应数据 1251 sendAndResponseAsStream(method, headers, timeout, output); 1252 } 1253 1254 /** 1255 * 发送请求数据,并接收响应数据 1256 * @param method 请求方式 1257 * @param headers 请求头信息 1258 * @param timeout 超时时间 1259 * @param output 响应内容(输出流) 1260 * @throws IOException 1261 */ 1262 private void sendAndResponseAsStream(HttpRequestBase method, 1263 Map<String, String> headers, int timeout, OutputStream output) throws IOException { 1264 // 设置请求配置信息 1265 RequestConfig config = RequestConfig.custom() 1266 .setConnectTimeout(DEFAULT_CONNECTION_TIMEOUT) //连接超时时间 1267 .setSocketTimeout(timeout) //读取超时时间 1268 .setCircularRedirectsAllowed(true) //设置是否允许循环重定向(重定向到相同路径) 1269 .build(); 1270 method.setConfig(config); 1271 1272 // 设置请求头信息 1273 if (headers == null) { 1274 headers = new HashMap<String, String>(); 1275 } 1276 if (!headers.containsKey(USER_AGENT)) { 1277 headers.put(USER_AGENT, DEFAULT_USERAGENT); 1278 } 1279 for (Map.Entry<String, String> entry : headers.entrySet()) { 1280 method.setHeader(entry.getKey(), entry.getValue()); 1281 } 1282 1283 // 发送请求 1284 CloseableHttpClient httpClient = createHttpClient(method.getURI()); 1285 CloseableHttpResponse httpResponse = null; 1286 InputStream input = null; 1287 try { 1288 httpResponse = httpClient.execute(method); 1289 int status = httpResponse.getStatusLine().getStatusCode(); 1290 if (status != HttpStatus.SC_OK) { 1291 String errorMsg = CustomStringUtils.append("The remote service[", 1292 method.getURI(), "] respose an error status:", status); 1293 logger.error(errorMsg); 1294 if (status >= 500 && status < 600) { 1295 throw new IOException(errorMsg); 1296 } 1297 } 1298 HttpEntity httpEntity = httpResponse.getEntity(); 1299 if (httpEntity == null) { 1300 String errorMsg = CustomStringUtils.append("The remote service[", 1301 method.getURI(), "] respose entity is null. status:", status); 1302 logger.error(errorMsg); 1303 throw new IOException(errorMsg); 1304 } 1305 input = httpEntity.getContent(); 1306 if (input == null) { 1307 String errorMsg = CustomStringUtils.append("The remote service[", 1308 method.getURI(), "] respose entity content is null. status:", status); 1309 logger.error(errorMsg); 1310 throw new IOException(errorMsg); 1311 } 1312 IOUtils.copy(input, output); 1313 } catch (IOException e) { 1314 logger.error("Access to the remote service[" + method.getURI() + "] error.", e); 1315 throw e; 1316 } finally { 1317 IOUtils.closeQuietly(input); 1318// method.releaseConnection(); 1319 IOUtils.closeQuietly(httpResponse); 1320 IOUtils.closeQuietly(httpClient); 1321 } 1322 } 1323 1324 /** 1325 * 创建HttpClient对象 1326 * @param uri 1327 * @return 1328 */ 1329 private CloseableHttpClient createHttpClient(URI uri) { 1330 if ("https".equalsIgnoreCase(uri.getScheme()) && sslSocketFactory != null) { 1331 return HttpClients.custom().setSSLSocketFactory(sslSocketFactory).build(); 1332 } else { 1333 return HttpClients.createDefault(); 1334 } 1335 } 1336 1337 /** 1338 * 创建请求URI 1339 * @param url 1340 * @param params 1341 * @param charsetName 1342 * @return 1343 * @throws IOException 1344 */ 1345 private URI createURI(String url, 1346 Map<String, String> params, String charsetName) throws IOException { 1347 if (params == null || params.isEmpty()) { 1348 return URI.create(url); 1349 } 1350 // 设置请求参数 1351 List<NameValuePair> parameters = new ArrayList<NameValuePair>(params.size()); 1352 for (Map.Entry<String, String> entry : params.entrySet()) { 1353 parameters.add(new BasicNameValuePair(entry.getKey(), entry.getValue())); 1354 } 1355 try { 1356 return new URIBuilder(url) 1357 .addParameters(parameters) 1358 .setCharset(Charset.forName(charsetName)) 1359 .build(); 1360 } catch (URISyntaxException e) { 1361 String errorMsg = "Build request URI error, the url is [" + url + "]."; 1362 logger.error(errorMsg, e); 1363 throw new IOException(errorMsg, e); 1364 } 1365 } 1366 1367 /** 1368 * @see PCIHttpClient.com.bestpay.pgw.tools.http.PGWHttpClient#sendGet(java.lang.String, java.util.Map, java.util.Map, java.lang.String, int) 1369 */ 1370 @Override 1371 public PCIHttpResponse sendGet(String url, Map<String, String> headers, 1372 Map<String, String> params, String charsetName, int timeout) 1373 throws IOException { 1374 if (StringUtils.isEmpty(url)) { 1375 logger.error("The url can not be null."); 1376 throw new IllegalArgumentException("The url can not be null."); 1377 } 1378 return sendAndResponseAsStream( 1379 new HttpGet(createURI(url, params, charsetName)), headers, timeout); 1380 } 1381 1382 /** 1383 * @see PCIHttpClient.com.bestpay.pgw.tools.http.PGWHttpClient#sendPost(java.lang.String, java.util.Map, java.util.Map, java.lang.Object, java.lang.String, int) 1384 */ 1385 @Override 1386 public PCIHttpResponse sendPost(String url, Map<String, String> headers, 1387 Map<String, String> params, Object stringOrStream, 1388 String charsetName, int timeout) throws IOException { 1389 if (StringUtils.isEmpty(url)) { 1390 logger.error("The url can not be null."); 1391 throw new IllegalArgumentException("The url can not be null."); 1392 } 1393 1394 // post请求方式 1395 HttpPost method = new HttpPost(createURI(url, params, charsetName)); 1396 1397 // 设置请求头信息 1398 if (headers == null) { 1399 headers = new HashMap<String, String>(); 1400 } 1401 if (!headers.containsKey(CONTENT_TYPE)) { 1402 headers.put(CONTENT_TYPE, DEFAULT_CONTENTTYPE); 1403 } 1404 1405 // 设置请求体内容 1406 if (stringOrStream != null) { 1407 HttpEntity entity = null; 1408 if (stringOrStream instanceof InputStream) { 1409 entity = new InputStreamEntity((InputStream) stringOrStream); 1410 } else { 1411 entity = new StringEntity(stringOrStream.toString(), 1412 ContentType.create(CONTENT_TYPE, charsetName)); 1413 } 1414 method.setEntity(entity); 1415 } 1416 1417 // 发送请求数据,并接收响应数据 1418 return sendAndResponseAsStream(method, headers, timeout); 1419 } 1420 1421 /** 1422 * 发送请求数据,并接收响应数据 1423 * 1424 * @param method 请求方式 1425 * @param headers 请求头信息 1426 * @param timeout 超时时间 1427 * @return 1428 * @throws IOException 1429 * 1430 * @since 2.0.0 1431 */ 1432 private PCIHttpResponse sendAndResponseAsStream(HttpRequestBase method, 1433 Map<String, String> headers, int timeout) throws IOException { 1434 // 设置请求配置信息 1435 RequestConfig config = RequestConfig.custom() 1436 .setConnectTimeout(DEFAULT_CONNECTION_TIMEOUT) //连接超时时间 1437 .setSocketTimeout(timeout) //读取超时时间 1438 .setCircularRedirectsAllowed(true) //设置是否允许循环重定向(重定向到相同路径) 1439 .build(); 1440 method.setConfig(config); 1441 1442 // 设置请求头信息 1443 if (headers == null) { 1444 headers = new HashMap<String, String>(); 1445 } 1446 if (!headers.containsKey(USER_AGENT)) { 1447 headers.put(USER_AGENT, DEFAULT_USERAGENT); 1448 } 1449 for (Map.Entry<String, String> entry : headers.entrySet()) { 1450 method.setHeader(entry.getKey(), entry.getValue()); 1451 } 1452 1453 // 发送请求 1454 CloseableHttpClient httpClient = createHttpClient(method.getURI()); 1455 CloseableHttpResponse httpResponse = null; 1456 InputStream responseBodyInputStream = null; 1457 ByteArrayOutputStream responseBodyOutputStream = null; 1458 try { 1459 httpResponse = httpClient.execute(method); 1460 int status = httpResponse.getStatusLine().getStatusCode(); 1461 if (status != HttpStatus.SC_OK) { 1462 String errorMsg = CustomStringUtils.append("The remote service[", 1463 method.getURI(), "] respose an error status:", status); 1464 logger.error(errorMsg); 1465 if (status >= 500 && status < 600) { 1466 throw new IOException(errorMsg); 1467 } 1468 } 1469 1470 // 获取响应头 1471 Map<String, String> responseHeaders = null; 1472 Header[] httpHeaders = httpResponse.getAllHeaders(); 1473 if (httpHeaders != null && httpHeaders.length > 0) { 1474 responseHeaders = new HashMap<String, String>(httpHeaders.length); 1475 for (Header header : httpHeaders) { 1476 responseHeaders.put(header.getName(), header.getValue()); 1477 } 1478 } 1479 1480 // 获取响应体 1481 byte[] responseBody = null; 1482 HttpEntity httpEntity = httpResponse.getEntity(); 1483 if (httpEntity != null) { 1484 responseBodyInputStream = httpEntity.getContent(); 1485 if (responseBodyInputStream != null) { 1486 responseBodyOutputStream = new ByteArrayOutputStream(); 1487 IOUtils.copy(responseBodyInputStream, responseBodyOutputStream); 1488 responseBody = responseBodyOutputStream.toByteArray(); 1489 } else { 1490 logger.warn(CustomStringUtils.append("The remote service[", 1491 method.getURI(), "] respose entity content is null. status:", status)); 1492 } 1493 } else { 1494 logger.warn(CustomStringUtils.append("The remote service[", 1495 method.getURI(), "] respose entity is null. status:", status)); 1496 } 1497 1498 return new PCIHttpResponse(responseHeaders, responseBody); 1499 } catch (IOException e) { 1500 logger.error("Access to the remote service[" + method.getURI() + "] error.", e); 1501 throw e; 1502 } finally { 1503 IOUtils.closeQuietly(responseBodyInputStream); 1504 IOUtils.closeQuietly(responseBodyOutputStream); 1505// method.releaseConnection(); 1506 IOUtils.closeQuietly(httpResponse); 1507 IOUtils.closeQuietly(httpClient); 1508 } 1509 } 1510 1511}

单元测试示例(本示例为双向认证示例,单向认证则对应修改PCIHttpClientImpl4的构造参数即可):

1 @Test 2 public void testClock() throws Exception { 3 String testUrl = "https://mail.xxxxxx.com:8440/service"; 4 Map<String, String> map = new HashMap<String, String>(); 5 6 map.put("messageType", "2058"); 7 map.put("accessUser", "gxecard_test_user_zhengchuan"); 8 map.put("terminalNo", "1"); 9 10 String parameter = JSON.toJSONString(map); 11 String requestJson = "parameter=" + parameter; 12 System.out.println("requestJson:" + requestJson); 13 14// httpClient = new PCIHttpClientImpl4(true, false, 15// true, true, 16// "D:\\keystore.jks", "123456", "123456"); 17 18 19 //证书可以是jks格式也可以是p12格式 20 httpClient = new PCIHttpClientImpl4(true, false, 21 true, true, 22 "D:\\keystore.p12", "123456", "123456"); 23 24 PCIHttpResponse httpResponse = null; 25 httpResponse = httpClient.sendPost(testUrl, null, null, requestJson, "UTF-8", 55 * 1000); 26 27 System.out.println(httpResponse.getBodyString()); 28 }
点赞
收藏

评论区

加载中...

相关推荐

MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1

文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s

Oracle 分组与拼接字符串同时使用

SELECTT.,ROWNUMIDFROM(SELECTT.EMPLID,T.NAME,T.BU,T.REALDEPART,T.FORMATDATE,SUM(T.S0)S0,MAX(UPDATETIME)CREATETIME,LISTAGG(TOCHAR(

MySQL部分从库上面因为大量的临时表tmp_table造成慢查询

背景描述Time:20190124T00:08:14.70572408:00User@Host:@Id:Schema:sentrymetaLast_errno:0Killed:0Query_time:0.315758Lock_

皕杰报表之UUID

​在我们用皕杰报表工具设计填报报表时,如何在新增行里自动增加id呢?能新增整数排序id吗?目前可以在新增行里自动增加id,但只能用uuid函数增加UUID编码,不能新增整数排序id。uuid函数说明:获取一个UUID,可以在填报表中用来创建数据ID语法:uuid()或uuid(sep)参数说明:sep布尔值,生成的uuid中是否包含分隔符'',缺省为

手写Java HashMap源码

HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程22

swap空间的增减方法

(1)增大swap空间去激活swap交换区:swapoff v /dev/vg00/lvswap扩展交换lv:lvextend L 10G /dev/vg00/lvswap重新生成swap交换区:mkswap /dev/vg00/lvswap激活新生成的交换区:swapon v /dev/vg00/lvswap