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. KubeDL HostNetwork:加速分布式训练通信效率

    ​简介:ubeDL 为分布式训练作业带来了 HostNetwork 网络模式,支持计算节点之间通过宿主机网络相互通信以提升网络性能,同时适应 RDMA/SCC 等新型高性能数据中心架构的网络环境,此外 ...

  2. 重磅发布:微服务引擎 MSE 专业版

    简介: 性能提升 10 倍,更高的 SLA 保障,新用户限时抢购 8 折资源包. 微服务引擎 MSE 专业版发布,支持 Nacos 2.0 ,相比基础版,专业版具有更高的 SLA 保障,性能提升十倍, ...

  3. [GPT] 机器学习框架平台或框架的学习成本和友好程度排名?

      按照学习成本从高到低的顺序,大概如下: TensorFlow:虽然TensorFlow功能强大,但学习曲线比较陡峭,需要掌握一些深度学习的基本概念和数学知识. PyTorch:PyTorch相对而 ...

  4. Intel Pentium III CPU(Coppermine, Tualatin) L2 Cache Latency, Hardware Prefetch特性调查

    这几天,偶然的机会想到了困扰自己和其他网友多年的Intel Pentium III系列处理器缓存延迟(L2 Cache Latency),以及图拉丁核心版本是否支持硬件预取(Hardware Pref ...

  5. mac常用

    目录 Mac 删除键(Delete) 这三招你会吗?可大幅加快打字速度 Mac软件打开提示:已损坏,无法打开.您应该将它移到废纸娄 怎么解决? 卸载手动安装的软件 如何在Mac上使用Charles进行 ...

  6. linux的统计实现

    场景: 将下面的数据里category里的分类统计计数 数据源 es_ip10000.json {"_index":"order","_type&qu ...

  7. vue3创建工程

    创建 Vue3 项目的步骤如下: 安装 Node.js Vue3 需要依赖 Node.js 环境,因此需要先安装 Node.js.可以从官网下载 Node.js 的安装包并安装,也可以使用包管理器安装 ...

  8. 热烈祝贺 Splashtop 荣获“最佳远程办公解决方案”奖

    ​ 2021年2月,第十四届加拿大年度"经销商选择奖"落下帷幕.Splashtop在此次评选中荣获"最佳远程办公解决方案"奖,获得该奖项的还有微软和谷歌. 一直 ...

  9. Chrome 浏览器插件 Manifest.json V3 中权限(Permissions)字段解析

    一.权限(Permissions) 再使用拓展程序的 API 时,大多数的时候,需要在 manifest.json 文件中声明 permissions 字段. 一.权限类型 在 V3 版本中可以声明以 ...

  10. 通过 OpenAPI 部署 Npcf_PolicyAuthorization-PostAppSessions API Service

    目录 文章目录 目录 OpenAPI 部署步骤 OpenAPI 官方网站:https://github.com/OAI/OpenAPI-Specification 支持通过标准的 yaml 文件来生成 ...