Java代码忽略https证书:解决No subject alternative names present问题

import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import javax.net.ssl.*;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate; /**
* Java代码忽略https证书:解决No subject alternative names present问题
*/
public class HttpsUtils {
private static final Logger logger = LoggerFactory.getLogger(HttpsUtils.class); public static String get(String hosturl,String params,String contentType) throws IOException, KeyManagementException, NoSuchAlgorithmException {
HttpsURLConnection.setDefaultHostnameVerifier(new HttpsUtils().new NullHostNameVerifier());
SSLContext sc = SSLContext.getInstance("TLS");
sc.init(null, trustAllCerts, new SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
URL url = new URL(hosturl+"?"+params);
logger.info("参数:"+hosturl+"?"+params); // 打开restful链接
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");// POST GET PUT DELETE
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
conn.setRequestProperty("Content-Type", "text/plain;charset=utf-8"); // 设置访问提交模式,表单提交
// conn.setRequestProperty("Content-Type", "text/plain;charset=utf-8");
// conn.setRequestProperty("Content-Type",contentType);
conn.setConnectTimeout(130000);// 连接超时 单位毫秒
conn.setReadTimeout(130000);// 读取超时 单位毫秒 // 读取请求返回值
byte bytes[] = new byte[1024];
InputStream inStream = conn.getInputStream();
inStream.read(bytes, 0, inStream.available());
logger.info("返回结果:" + new String(bytes, "utf-8"));
return new String(bytes, "utf-8");
} /**
*
* @param hosturl
* @param params
* @param contentType text/plain;charset=utf-8 application/json;charset=utf-8
* @return
* @throws IOException
* @throws KeyManagementException
* @throws NoSuchAlgorithmException
*/
public static String post(String hosturl,String params,String contentType) {
StringBuffer result = new StringBuffer();
OutputStream os = null;
InputStream is = null;
BufferedReader br = null;
HttpURLConnection conn = null;
try {
HttpsURLConnection.setDefaultHostnameVerifier(new HttpsUtils().new NullHostNameVerifier());
SSLContext sc = SSLContext.getInstance("TLS");
sc.init(null, trustAllCerts, new SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
// URL url = new URL(hosturl+"?"+params);
// logger.info("参数:"+hosturl+"?"+params); URL url = new URL(hosturl);
logger.info("参数url:" + hosturl +",params:"+ params); // 打开restful链接
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");// POST GET PUT DELETE
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
conn.setRequestProperty("Content-Type", "text/plain;charset=utf-8"); // 设置访问提交模式,表单提交
// conn.setRequestProperty("Content-Type", "text/plain;charset=utf-8");
// conn.setRequestProperty("Content-Type",contentType);
conn.setConnectTimeout(130000);// 连接超时 单位毫秒
conn.setReadTimeout(130000);// 读取超时 单位毫秒
//DoOutput设置是否向httpUrlConnection输出,DoInput设置是否从httpUrlConnection读入,此外发送post请求必须设置这两个
//设置是否可读取
conn.setDoOutput(true);
conn.setDoInput(true); //拼装参数
if (null != params && !params.equals("")) {
//设置参数
os = conn.getOutputStream();
//拼装参数
os.write(params.getBytes("UTF-8"));
logger.info("发送请求参数成功,params:"+params);
} // 读取请求返回值,收不到返回??
// byte bytes[] = new byte[1024];
// InputStream inStream = conn.getInputStream();
// inStream.read(bytes, 0, inStream.available());
// logger.info("返回结果:" + new String(bytes, "utf-8"));
// return new String(bytes, "utf-8"); //读取响应
if (conn.getResponseCode() == 200) {
is = conn.getInputStream();
if (null != is) {
br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
String temp = null;
while (null != (temp = br.readLine())) {
result.append(temp);
result.append("\r\n");
}
}else{
logger.error("连接获取返回inputStream null");
}
} logger.info("responseCode:"+conn.getResponseCode()+"返回url:" + hosturl +",返回result:"+ result.toString()); }catch (Exception e) {
logger.error("post exception:",e);
}finally {
//关闭连接
if(br!=null){
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(os!=null){
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(is!=null){
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
//关闭连接
conn.disconnect();
}
return result.toString();
} /**
*
* @param hosturl
* @param params
* @param contentType
* @return
* @throws IOException
* @throws KeyManagementException
* @throws NoSuchAlgorithmException
*/
public static String postJson(String hosturl,String params,String contentType) {
StringBuffer result = new StringBuffer();
OutputStream os = null;
InputStream is = null;
BufferedReader br = null;
HttpURLConnection conn = null; try {
HttpsURLConnection.setDefaultHostnameVerifier(new HttpsUtils().new NullHostNameVerifier());
SSLContext sc = SSLContext.getInstance("TLS");
sc.init(null, trustAllCerts, new SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
URL url = new URL(hosturl);
logger.info("参数url:" + hosturl + ",params=" + params);
// 打开restful链接
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");// POST GET PUT DELETE
// 设置访问提交模式,表单提交
// conn.setRequestProperty("Content-Type", "text/plain;charset=utf-8");
// conn.setRequestProperty("Content-Type",contentType);
//设置通用的请求属性
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
conn.setRequestProperty("Content-Type", "application/json;charset=utf-8");
conn.setConnectTimeout(130000);// 连接超时 单位毫秒
conn.setReadTimeout(130000);// 读取超时 单位毫秒
//DoOutput设置是否向httpUrlConnection输出,DoInput设置是否从httpUrlConnection读入,此外发送post请求必须设置这两个
//设置是否可读取
conn.setDoOutput(true);
conn.setDoInput(true); //拼装参数
if (null != params && !params.equals("")) {
//设置参数
os = conn.getOutputStream();
//拼装参数
os.write(params.getBytes("UTF-8"));
logger.info("发送请求参数成功,params:"+params);
} //读取响应 // 读取请求返回值,收不到返回??
// if (conn.getResponseCode() == 200) {
// 读取请求返回值
// byte bytes[] = new byte[1024];
// InputStream inStream = conn.getInputStream();
// inStream.read(bytes, 0, inStream.available());
// logger.info("返回结果:" + new String(bytes, "utf-8"));
// return new String(bytes, "utf-8");
// }
// return null; //读取响应
if (conn.getResponseCode() == 200) {
is = conn.getInputStream();
if (null != is) {
br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
String temp = null;
while (null != (temp = br.readLine())) {
result.append(temp);
result.append("\r\n");
}
}else{
logger.error("连接获取返回inputStream null");
}
} logger.info("responseCode:"+conn.getResponseCode()+"返回url:" + hosturl +",返回result:"+ result.toString()); }catch (Exception e) {
logger.error("postJson exception:",e);
}finally {
//关闭连接
if(br!=null){
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(os!=null){
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(is!=null){
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
//关闭连接
conn.disconnect();
}
return result.toString();
} static TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
// TODO Auto-generated method stub
} @Override
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
// TODO Auto-generated method stub
} @Override
public X509Certificate[] getAcceptedIssuers() {
// TODO Auto-generated method stub
return null;
}
} }; public class NullHostNameVerifier implements HostnameVerifier {
/*
* (non-Javadoc)
*
* @see javax.net.ssl.HostnameVerifier#verify(java.lang.String,
* javax.net.ssl.SSLSession)
*/
@Override
public boolean verify(String arg0, SSLSession arg1) {
// TODO Auto-generated method stub
return true;
}
} }

Java代码忽略https证书:解决No subject alternative names present问题 HttpURLConnection https请求的更多相关文章

  1. 【java细节】Java代码忽略https证书:No subject alternative names present

    https://blog.csdn.net/audioo1/article/details/51746333

  2. JDK安全证书的一个错误消息 No subject alternative names present的解决办法

    我使用Java消费某网站一个Restful API时,遇到这个错误: 21:31:16.383 [main] DEBUG org.springframework.web.client.RestTemp ...

  3. java.security.cert.CertificateException: No subject alternative names present

    背景:在开发一个项目中,要调用一个webservice服务,之前设置的是http协议,项目中采用jdk自带的wsimport工具生成的客户端代码; 后来,需求变更要求兼容https协议的webserv ...

  4. SpringBoot 连接kafka ssl 报 CertificateException: No subject alternative names present 异常解决

    当使用较新版本SpringBoot时,对应的 kafka-client 版本也比较新,如果使用了 2.x 以上的 kafka-client ,并且配置了 kafka ssl 连接方式时,可能会报如下异 ...

  5. MQTT研究之EMQ:【JAVA代码构建X509证书【续集】】

    openssl创建私钥,获取公钥,创建证书都是比较简单的,就几个指令,很快就可以搞定,之所以说简单,是因为证书里面的基本参数配置不需要我们组装,只需要将命令行里面需要的几个参数配置进去即可.但是呢,用 ...

  6. 用HttpClient发送HTTPS请求报SSLException: Certificate for <域名> doesn't match any of the subject alternative names问题的解决

    最近用server酱-PushBear做消息自动推送,用apache HttpClient做https的get请求,但是代码上到服务器端就报javax.net.ssl.SSLException: Ce ...

  7. 使用HttpClient携带证书报错_Certificate for <IP> doesn't match any of the subject alternative names:[域名]

    使用HttpClient携带pfx证书通过Https协议发送SOUP报文调用WebService接口时报如下错误: Exception in thread "main" javax ...

  8. Aandroid 解决apk打包过程中出现的“Certificate for <jcenter.bintray.com> doesn't match any of the subject alternative names: [*.aktana.com, aktana.com]”的问题

    有时候,apk打包过程中会出现“Certificate for <jcenter.bintray.com> doesn't match any of the subject alterna ...

  9. MQTT研究之EMQ:【JAVA代码构建X509证书】

    这篇帖子,不会过多解释X509证书的基础理论知识,也不会介绍太多SSL/TLS的基本信息,重点介绍如何用java实现SSL协议需要的X509规范的证书. 之前的博文,介绍过用openssl创建证书,并 ...

  10. 【转载】网站配置Https证书系列(二):IIS服务器给网站配置Https证书

    针对网站的Https证书,即SSL证书,腾讯云.阿里云都提供了免费的SSL证书申请,SSL证书申请下来后,就需要将SSL证书配置到网站中,如果网站使用的Web服务器是IIS服务器,则需要在IIS服务器 ...

随机推荐

  1. PyFlink 教程(三):PyFlink DataStream API - state & timer

    简介: 介绍如何在 Python DataStream API 中使用 state & timer 功能. 一.背景 Flink 1.13 已于近期正式发布,超过 200 名贡献者参与了 Fl ...

  2. 巧用友盟+U-APM 实现移动端性能优化—启动速度

    ​简介: 移动端性能对用户体验.留存有着至关重要的影响,作为开发者是不是被这样吐槽过,"这个 APP 怎么这么大?"."怎么一直在 APP 封面图转悠,点不进去" ...

  3. 还在为多集群管理烦恼吗?RedHat 和蚂蚁、阿里云给开源社区带来了OCM

    简介: 为了让开发者.用户在多集群和混合环境下也能像在单个 Kubernetes 集群平台上一样,使用自己熟悉的开源项目和产品轻松开发功能,RedHat 和蚂蚁.阿里云共同发起并开源了 OCM(Ope ...

  4. [FAQ] golang-migrate/migrate error: default addr for network '127.0.0.1:3306' unknown

    按照项目github文档上所示,在使用 mysql 时你可能会这样写: $ migrate -path db/migrations -database mysql://root:123456@127. ...

  5. dotnet Roslyn 通过读取 suo 文件获取解决方案的启动项目

    本文来告诉大家一个黑科技,通过 .suo 文件读取 VisualStudio 的启动项目.在 sln 项目里面,都会生成对应的 suo 文件,这个文件是 OLE 格式的文件,文件的格式没有公开,本文的 ...

  6. 什么是IPD项目管理模式?聊聊IPD下的产品研发流程

    IPD(集成产品开发)涵盖了产品从创意提出到研发.生产.运营等,包含了产品开发到营销运营的整个过程.围绕产品(或项目)生命周期的过程的管理模式,是一套生产流程,更是时下国际先进的管理体系.IPD(集成 ...

  7. 如何通过前后端交互的方式制作Excel报表

    前言 Excel拥有在办公领域最广泛的受众群体,以其强大的数据处理和可视化功能,成了无可替代的工具.它不仅可以呈现数据清晰明了,还能进行数据分析.图表制作和数据透视等操作,为用户提供了全面的数据展示和 ...

  8. ansible系列(26)--ansible的tags标签

    目录 1. tags标签 1.1 指定执行某个tags 1.2 指定排除某个tags 1. tags标签 默认情况下, Ansible 在执行一个 playbook 时,会执行 playbook 中所 ...

  9. Pageoffice6 实现后台批量生成Word文档

    在实际项目开发中经常会遇到后台动态生成文档的需求,目前网上有一些针对此需求的方案,如果您想要了解这些方案的对比,请查看后台生成单个Word文档中的"方案对比". 如果一次只生成一份 ...

  10. jenkens

    [root@mcw01 ~]$ ls .jenkins/ config.xml jenkins.install.UpgradeWizard.state nodeMonitors.xml secret. ...