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. 那些你不知道的TCP冷门知识!

    简介: 最近在做数据库相关的事情,碰到了很多TCP相关的问题,新的场景新的挑战,有很多之前并没有掌握透彻的点,大大开了一把眼界,选了几个案例分享一下. 最近在做数据库相关的事情,碰到了很多TCP相关的 ...

  2. Gartner APM 魔力象限技术解读——全量存储? No! 按需存储?YES!

    简介: 在云原生时代,充分利用边缘节点的计算和存储能力,结合冷热数据分离实现高性价比的数据价值探索已经逐渐成为 APM 领域的主流. 作者:夏明(涯海) 调用链记录了完整的请求状态及流转信息,是一座巨 ...

  3. dotnet SemanticKernel 入门 注入日志

    使用 SemanticKernel 框架在对接 AI 时,由于使用到了大量的魔法,需要有日志的帮助才好更方便定位问题,本文将告诉大家如何在 SemanticKernel 注入日志 本文属于 Seman ...

  4. 修复 VisualStudio 构建时没有将 NuGet 的 PDB 符号文件拷贝到输出文件夹

    本文告诉大家如何修复 VisualStudio 构建时没有将 NuGet 的 PDB 符号文件拷贝到输出文件夹的问题.如果 VisualStudio 构建时没有将 NuGet 的 PDB 符号文件拷贝 ...

  5. python实现打扑克方法

    # 游戏规则:# 一付扑克牌,去掉大小王,每个玩家发3张牌,最后比大小,看谁赢.## 有以下几种牌:# 豹子:三张一样的牌,如3张6.# 同花顺:即3张同样花色的顺子, 如红桃 5.6.7# 顺子:又 ...

  6. Jenkins 简述及其搭建

    什么是持续集成? 持续集成(CI)是在软件开发过程中自动化和集成许多团队成员的代码更改和更新的过程.在 CI 中,自动化工具在集成之前确认软件代码是有效且无错误的,这有助于检测错误并加快新版本的发布. ...

  7. netcore5下js请求跨域

    后端代码如下: using Microsoft.AspNetCore.Mvc; using System; using System.Collections.Generic; using System ...

  8. SQL语法之:连表查询:union all

    1.准备 两条sql查询出来的字段数必须一致 表1 字段: 数据: 表2 字段: 数据: 2.使用 1.两张表结构完全一样,查询字段顺序也一样 select ID,NAME,SEX,AGE,NAME2 ...

  9. 【GUI软件】小红书按关键词采集笔记详情,支持多个关键词,含笔记正文、转评赞藏等

    目录 一.背景介绍 1.1 爬取目标 1.2 演示视频 1.3 软件说明 二.代码讲解 2.1 爬虫采集-搜索接口 2.2 爬虫采集-详情接口 2.3 cookie说明 2.4 软件界面模块 2.5 ...

  10. 04.2 go-admin前后端打包为一个服务上线

    目录 一.思路: 二.打包go-admin-ui为静态文件 a.修改配置文件 b.打包 c.复制dist到go-admin的static目录里 三.配置go-admin a.配置路由 b.访问页面 视 ...