1. import org.apache.commons.collections.MapUtils;
  2. import org.apache.http.*;
  3. import org.apache.http.client.entity.UrlEncodedFormEntity;
  4. import org.apache.http.client.methods.HttpPost;
  5. import org.apache.http.config.Registry;
  6. import org.apache.http.config.RegistryBuilder;
  7. import org.apache.http.conn.socket.ConnectionSocketFactory;
  8. import org.apache.http.conn.socket.PlainConnectionSocketFactory;
  9. import org.apache.http.conn.ssl.NoopHostnameVerifier;
  10. import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
  11. import org.apache.http.conn.ssl.TrustStrategy;
  12. import org.apache.http.impl.client.CloseableHttpClient;
  13. import org.apache.http.impl.client.HttpClients;
  14. import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
  15. import org.apache.http.message.BasicNameValuePair;
  16. import org.apache.http.ssl.SSLContextBuilder;
  17. import org.apache.http.util.EntityUtils;
  18. import java.io.IOException;
  19. import java.security.cert.CertificateException;
  20. import java.security.cert.X509Certificate;
  21. import java.util.ArrayList;
  22. import java.util.List;
  23. import java.util.Map;
  24. public class HttpsUtils {
  25. private static final String HTTP = "http";
  26. private static final String HTTPS = "https";
  27. private static SSLConnectionSocketFactory sslsf = null;
  28. private static PoolingHttpClientConnectionManager cm = null;
  29. private static SSLContextBuilder builder = null;
  30. static {
  31. try {
  32. builder = new SSLContextBuilder();
  33. // 全部信任 不做身份鉴定
  34. builder.loadTrustMaterial(null, new TrustStrategy() {
  35. @Override
  36. public boolean isTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
  37. return true;
  38. }
  39. });
  40. sslsf = new SSLConnectionSocketFactory(builder.build(), new String[]{"SSLv2Hello", "SSLv3", "TLSv1", "TLSv1.2"}, null, NoopHostnameVerifier.INSTANCE);
  41. Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
  42. .register(HTTP, new PlainConnectionSocketFactory())
  43. .register(HTTPS, sslsf)
  44. .build();
  45. cm = new PoolingHttpClientConnectionManager(registry);
  46. cm.setMaxTotal(200);//max connection
  47. } catch (Exception e) {
  48. e.printStackTrace();
  49. }
  50. }
  51. /**
  52. * httpClient post请求
  53. * @param url 请求url
  54. * @param header 头部信息
  55. * @param param 请求参数 form提交适用
  56. * @param entity 请求实体 json/xml提交适用
  57. * @return 可能为空 需要处理
  58. * @throws Exception
  59. *
  60. */
  61. public static String post(String url, Map<String, String> header, Map<String, String> param, HttpEntity entity) throws Exception {
  62. String result = "";
  63. CloseableHttpClient httpClient = null;
  64. try {
  65. httpClient = getHttpClient();
  66. HttpPost httpPost = new HttpPost(url);
  67. // 设置头信息
  68. if (MapUtils.isNotEmpty(header)) {
  69. for (Map.Entry<String, String> entry : header.entrySet()) {
  70. httpPost.addHeader(entry.getKey(), entry.getValue());
  71. }
  72. }
  73. // 设置请求参数
  74. if (MapUtils.isNotEmpty(param)) {
  75. List<NameValuePair> formparams = new ArrayList<NameValuePair>();
  76. for (Map.Entry<String, String> entry : param.entrySet()) {
  77. //给参数赋值
  78. formparams.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
  79. }
  80. UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(formparams, Consts.UTF_8);
  81. httpPost.setEntity(urlEncodedFormEntity);
  82. }
  83. // 设置实体 优先级高
  84. if (entity != null) {
  85. httpPost.setEntity(entity);
  86. }
  87. HttpResponse httpResponse = httpClient.execute(httpPost);
  88. int statusCode = httpResponse.getStatusLine().getStatusCode();
  89. if (statusCode == HttpStatus.SC_OK) {
  90. HttpEntity resEntity = httpResponse.getEntity();
  91. result = EntityUtils.toString(resEntity);
  92. } else {
             readHttpResponse(httpResponse);
  93. }
  94. } catch (Exception e) {throw e;
  95. } finally {
  96. if (httpClient != null) {
  97. httpClient.close();
  98. }
  99. }
  100. return result;
  101. }
  102. public static CloseableHttpClient getHttpClient() throws Exception {
  103. CloseableHttpClient httpClient = HttpClients.custom()
  104. .setSSLSocketFactory(sslsf)
  105. .setConnectionManager(cm)
  106. .setConnectionManagerShared(true)
  107. .build();
  108. return httpClient;
  109. }
  110. public static String readHttpResponse(HttpResponse httpResponse)
  111. throws ParseException, IOException {
  112. StringBuilder builder = new StringBuilder();
  113. // 获取响应消息实体
  114. HttpEntity entity = httpResponse.getEntity();
  115. // 响应状态
  116. builder.append("status:" + httpResponse.getStatusLine());
  117. builder.append("headers:");
  118. HeaderIterator iterator = httpResponse.headerIterator();
  119. while (iterator.hasNext()) {
  120. builder.append("\t" + iterator.next());
  121. }
  122. // 判断响应实体是否为空
  123. if (entity != null) {
  124. String responseString = EntityUtils.toString(entity);
  125. builder.append("response length:" + responseString.length());
  126. builder.append("response content:" + responseString.replace("\r\n", ""));
  127. }
  128. return builder.toString();
  129. }
  130. }

httpclient4.5 https请求 忽略身份验证的更多相关文章

  1. WCF:无法满足对安全令牌的请求,因为身份验证失败。

    服务端和客户端如果有认证的话的这样: <wsHttpBinding> <binding name="WSHttpBinding_IService1" closeT ...

  2. httpclient 3.1跳过https请求SSL的验证

    一.因为在使用https发送请求的时候会涉及,验证方式.但是这种方式在使用的时候很不方便.特别是在请求外部接口的时候,所以这我写了一个跳过验证的方式.(供参考) 二.加入包,这里用的是commons- ...

  3. linux c++ curl https 请求并双向验证SSL证书

    1.配置curl https请求需要提供 CA证书.客户端证书和客户端秘钥,这三个文件的pem格式. 分别对应 curl_easy_setopt() 函数的 下面三个参数: CURLOPT_CAINF ...

  4. HTTPS请求 SSL证书验证

    import urllib2 url = "https://www.12306.cn/mormhweb/" headers = {"User-Agent": & ...

  5. jdk1.6 支持 tls1.2协议 并忽略身份验证

    jdk1.6不支持tls1.2协议,jdk1.8默认支持,比较好的解决方案是升级jdk,但是升级jdk风险极大.不能升级jdk的情况下,可以使用如下方式. 引入依赖 <dependency> ...

  6. Mysql 连接提示 Client does not support authentication protocol requested by server 客户端不支持服务器请求的身份验证协议;考虑升级MySQL客户端

    由于查阅了很多百度文档发现很多方法比较复杂,所以写个备忘: 首先,进入MySQL 8.0Command Line Client -Unicode,输入密码,登录进去. 然后,在命令行输入:ALTER ...

  7. requests发送HTTPS请求(处理SSL证书验证)

    1.SSL是什么,为什么发送HTTPS请求时需要证书验证? 1.1 SSL:安全套接字层.是为了解决HTTP协议是明文,避免传输的数据被窃取,篡改,劫持等. 1.2 TSL:Transport Lay ...

  8. [转]Reporting Services 中的身份验证类型

    本文转自:https://docs.microsoft.com/zh-cn/previous-versions/sql/sql-server-2008/cc281310%28v%3dsql.100%2 ...

  9. ASP.NET没有魔法——ASP.NET Identity 的“多重”身份验证

    ASP.NET Identity除了提供基于Cookie的身份验证外,还提供了一些高级功能,如多次输入错误账户信息后会锁定用户禁止登录.集成第三方验证.账户的二次验证等,并且ASP.NET MVC的默 ...

随机推荐

  1. IIS上架设https网站证书处理备忘

    1. 免费SSL证书申请 https://www.startssl.com 教程:http://hxs.fd.fj.cn/?action=show&id=13 2. 证书转换 申请到的证书有两 ...

  2. 中国大陆被SCI收录的较高影响力期刊

    1.清华主办的期刊Nano Research 清华新闻网2012年9月10日电:据汤森路透公司公布的2011年SCI期刊影响因子,清华大学主办的期刊Nano Research(纳米研究)的影响因子为6 ...

  3. [Jenkins]怎样在Jenkins上面启动服务器上的批处理脚本

    New Item 在Build --> Execute Windows batch command --> 里面填写: schtasks /run /tn Start_Hub_szotqa ...

  4. Please do not register multiple Pages in undefined.js 小程序报错的几种解决方案

    Wed Jun 27 2018 09:25:43 GMT+0800 (中国标准时间) Page 注册错误,Please do not register multiple Pages in undefi ...

  5. WebApi参数传递总结(转)

    出处:http://www.cnblogs.com/Juvy/p/3903974.html 在WebAPI中,请求主体(HttpContent)只能被读取一次,不被缓存,只能向前读取的流. 举例子说明 ...

  6. System.Web.HttpUtility VS System.Web.HttpServerUtility VS System.Net.WebUtility

    HttpUtility 类作为 HttpServerUtility 类的内部使用,HttpServerUtility 通过System.Web.UI.Page.Server属性(WebForm)/Co ...

  7. Linux网络(一)

    [root@localhost ~]# ifconfig eth0 Link encap:Ethernet HWaddr :0C:::F6: inet addr:172.17.4.128 Bcast: ...

  8. 密码分析:使用 Ettercap 和 它的 ARP 毒化功能来嗅探流量

    vim /etc/etterconf 将 ec_uid 和 ec_gid 改为 0 需要取消下面的 IPTABLES 行的注释.它在靠近文件末尾的 LINUX 一节 ettercap -G Shift ...

  9. CLOB 和 BLOB

    An SQL CLOB is a built-in type that stores a Character Large Object as a column value in a row of a ...

  10. [转]WCF体系结构-一张图就是好

    本文转自:http://www.cnblogs.com/snakevash/archive/2011/05/02/2034414.html 今天在MSDN上面看到了这么一张图,让我顿时感觉脑袋清醒很多 ...