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. WPF 已知问题 某些设备上的应用在 WindowChromeWorker 抛出 System.OverflowException 异常

    准确来说,这个不算是 WPF 的问题,而是系统等的问题.在某些设备上的使用了 WindowChrome 功能的 WPF 应用,将在运行过程,在 WindowChromeWorker 类里面抛出 Sys ...

  2. 提取jks文件证书和私钥

    提取jks文件证书和私钥 JKS文件由公钥和密钥构成利用Java Keytool 工具生成的文件,它是由公钥和密钥构成的,公钥就是我们平时说的证书(.cer后缀的文件),私钥就是密钥(.key后缀的文 ...

  3. 使用openvp*-gui客户端连接多服务端,作为Windows服务部署

    背景 多数公司都会用到VPN隧道技术链接服务器,保证服务器的安全,但多数情况下会存在多服务端的情况,这时就有客户端连接多个服务端的必要了,如果每次都要切换配置的话,对于有强迫症的兄弟当然忍不了了 思考 ...

  4. 【GUI开发】用python爬YouTube博主信息,并开发成exe软件!

    目录 一.背景介绍 二.代码讲解 2.1 爬虫 2.2 tkinter界面 2.3 存日志 三.说明 一.背景介绍 你好,我是@马哥python说,一名10年程序猿. 最近我用python开发了一个G ...

  5. layui表单验证抽离成单独模块手动调用

    模块名:validateForm 验证添加方法和原来一样(lay-verify=''),可以多个表单一起验证,任何任何一个验证不通过就会返回.使用: var boolResult = validate ...

  6. linux cd命令的重要用法:cd -,cd ~

    cd命令的作用:进入磁盘的某个目录下. [root@node5 ~]# cd /etc/sysconfig/network-scripts/ [root@node5 network-scripts]# ...

  7. PhiData 一款开发AI搜索、agents智能体和工作流应用的AI框架

    引言 在人工智能领域,构建一个能够理解并响应用户需求的智能助手是一项挑战性的任务.PhiData作为一个开源框架,为开发者提供了构建具有长期记忆.丰富知识和强大工具的AI助手的可能性.本文将介绍Phi ...

  8. Lakehouse 还是 Warehouse?(1/2)

    Onehouse 创始人/首席执行官 Vinoth Chandar 于 2022 年 3 月在奥斯汀数据委员会发表了这一重要演讲.奥斯汀数据委员会是"世界上最大的独立全栈数据会议" ...

  9. 阿里巴巴 MySQL 数据库之 SQL 语句规约 (三)

    SQL 语句规约 强制部分 [强制] 不要使用 count(列名) 或 count(常量) 来替代 count(*),count(*) 是 SQL92 定义的标准统计行数的语法,跟数据库无关,跟 NU ...

  10. 一文教你如何调用Ascend C算子

    本文分享自华为云社区<一文教你如何调用Ascend C算子>,作者: 昇腾CANN. Ascend C是CANN针对算子开发场景推出的编程语言,原生支持C和C++标准规范,兼具开发效率和运 ...