HttpUtils.java 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154
  1. package com.pj.api.pushfee.tools;
  2. import org.apache.http.HttpEntity;
  3. import org.apache.http.HttpResponse;
  4. import org.apache.http.client.HttpClient;
  5. import org.apache.http.client.config.AuthSchemes;
  6. import org.apache.http.client.config.CookieSpecs;
  7. import org.apache.http.client.config.RequestConfig;
  8. import org.apache.http.client.methods.HttpGet;
  9. import org.apache.http.client.methods.HttpPost;
  10. import org.apache.http.config.Registry;
  11. import org.apache.http.config.RegistryBuilder;
  12. import org.apache.http.conn.socket.ConnectionSocketFactory;
  13. import org.apache.http.conn.socket.PlainConnectionSocketFactory;
  14. import org.apache.http.conn.ssl.NoopHostnameVerifier;
  15. import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
  16. import org.apache.http.entity.BufferedHttpEntity;
  17. import org.apache.http.entity.StringEntity;
  18. import org.apache.http.impl.client.HttpClients;
  19. import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
  20. import javax.net.ssl.SSLContext;
  21. import javax.net.ssl.TrustManager;
  22. import javax.net.ssl.X509TrustManager;
  23. import java.io.IOException;
  24. import java.io.InputStreamReader;
  25. import java.security.KeyManagementException;
  26. import java.security.NoSuchAlgorithmException;
  27. import java.security.cert.CertificateException;
  28. import java.security.cert.X509Certificate;
  29. import java.util.Arrays;
  30. public class HttpUtils {
  31. private static String DEFAULT_ENCODING = "UTF-8";
  32. private static HttpClient getClientNoSSL() {
  33. try {
  34. SSLContext ctx = SSLContext.getInstance(SSLConnectionSocketFactory.TLS);
  35. ctx.init(null, new TrustManager[] { new MyTrustManager() }, null);
  36. SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(ctx, NoopHostnameVerifier.INSTANCE);
  37. // 创建Registry
  38. RequestConfig requestConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD_STRICT)
  39. .setExpectContinueEnabled(Boolean.TRUE).setTargetPreferredAuthSchemes(Arrays.asList(AuthSchemes.NTLM,AuthSchemes.DIGEST))
  40. .setProxyPreferredAuthSchemes(Arrays.asList(AuthSchemes.BASIC)).build();
  41. Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
  42. .register("http", PlainConnectionSocketFactory.INSTANCE)
  43. .register("https",socketFactory).build();
  44. // 创建ConnectionManager,添加Connection配置信息
  45. PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
  46. HttpClient closeableHttpClient = HttpClients.custom().setConnectionManager(connectionManager)
  47. .setDefaultRequestConfig(requestConfig).build();
  48. return closeableHttpClient;
  49. } catch (KeyManagementException e) {
  50. throw new RuntimeException(e);
  51. } catch (NoSuchAlgorithmException e) {
  52. throw new RuntimeException(e);
  53. }
  54. }
  55. /***
  56. * 提交具有加密的https或http Post请求
  57. * @param url 请求url
  58. * @param jsonEntity 请求体
  59. * @throws IOException
  60. */
  61. public static String doPostWithOpenApi(String url, String jsonEntity) throws IOException {
  62. HttpClient httpClient = getClientNoSSL();
  63. HttpResponse response = null;
  64. try {
  65. HttpPost post = new HttpPost(url);
  66. post.setHeader("contentType", "application/json;charset=UTF-8");
  67. post.setHeader("Authorization", "openApi");
  68. StringEntity entity = new StringEntity(jsonEntity);
  69. entity.setContentEncoding(DEFAULT_ENCODING);
  70. entity.setContentType("application/json");
  71. //提交json串
  72. BufferedHttpEntity bufferedHttpEntity = new BufferedHttpEntity(entity);
  73. post.setEntity(bufferedHttpEntity);
  74. response = httpClient.execute(post);
  75. } catch (IOException e) {
  76. e.printStackTrace();
  77. }
  78. if (response.getStatusLine().getStatusCode() == 200) {
  79. return getResponseAsString(response);
  80. }else {
  81. return getResponseAsString(response);
  82. }
  83. }
  84. public static String doGet(String url) throws IOException {
  85. HttpClient httpClient = getClientNoSSL();
  86. HttpResponse response = null;
  87. try {
  88. HttpGet get = new HttpGet(url);
  89. get.setHeader("contentType", "application/json;charset=UTF-8");
  90. response = httpClient.execute(get);
  91. } catch (IOException e) {
  92. e.printStackTrace();
  93. }
  94. if (response.getStatusLine().getStatusCode() == 200) {
  95. return getResponseAsString(response);
  96. }else {
  97. return getResponseAsString(response);
  98. }
  99. }
  100. /**
  101. * 将response响应消息转换为字符串
  102. * @param response
  103. * @return
  104. * @throws IOException
  105. */
  106. public static String getResponseAsString(HttpResponse response) throws IOException {
  107. String result = "";
  108. HttpEntity resEntity = response.getEntity();
  109. InputStreamReader reader = new InputStreamReader(resEntity.getContent());
  110. char[] buff = new char[1024];
  111. int length = 0;
  112. while ((length = reader.read(buff)) != -1) {
  113. result += new String(buff, 0, length);
  114. }
  115. return result;
  116. }
  117. }
  118. /**
  119. * 自定义重写自动接收所有证书
  120. */
  121. class MyTrustManager implements X509TrustManager {
  122. public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
  123. }
  124. public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
  125. }
  126. public X509Certificate[] getAcceptedIssuers() {
  127. return new X509Certificate[0];
  128. }
  129. }