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. Spring Boot Serverless 实战 | Serverless 应用的监控与调试

    ​简介:Spring Boot 是基于 Java Spring 框架的套件,它预装了 Spring 的一系列组件,让开发者只需要很少的配置就可以创建独立运行的应用程序.在云原生的环境中,有大量的平台可 ...

  2. Vineyard 加入 CNCF Sandbox,将继续瞄准云原生大数据分析领域

    简介: Vineyard 是一个专为云原生环境下大数据分析场景中端到端工作流提供内存数据共享的分布式引擎,我们很高兴宣布 Vineyard 在 2021 年 4 月 27 日被云原生基金会(CNCF) ...

  3. [GPT] 使用 nodejs的 puppeteer 库使用完关闭后,linux上面有很多 chrome 进程

      在使用 Node.js 的 Puppeteer 库时,如果你在使用完后关闭了浏览器,但在 Linux 上仍然存在很多 Chrome 进程,可能是因为没有正确地关闭所有相关的进程. 可以尝试以下方法 ...

  4. dotnet 在 UOS 国产系统上使用 Xamarin Forms 创建 xaml 界面的 GTK 应用

    在前面几篇博客告诉大家如何部署 GTK 应用,此时的应用是特别弱的,大概只是到拖控件级.尽管和 WinForms 一样也能写出特别强大的应用,但是为了提升一点开发效率,咱开始使用 xaml 神器写界面 ...

  5. ABAP 7.55 新特性 (二) ABAP SQL部分

    上一篇文章ABAP 7.55 新特性 (一)介绍了ABAP 7.55中除ABAP SQL外的更新内容,本篇是剩余的ABAP SQL更新部分. 本文链接:https://www.cnblogs.com/ ...

  6. 《最新出炉》系列入门篇-Python+Playwright自动化测试-46-鼠标滚轮操作

    1.简介 有些网站为了节省流量和资源,提高加载效率,采用的是动态加载(懒加载)的,也就是当拖动页面右侧滚动条后会自动加载网页下面的内容,不拖动就不会加载的或者通过鼠标滚轮操作. 2.wheel模拟鼠标 ...

  7. 2022年官网下安装ZooKeeper最全版与官网查阅方法

    目录 一.环境整合 构建工具(参考工具部署方式) 二.官网下载 三.解压安装 四.配置环境 五.启动运行 六.配置为服务 七.查看设置服务 其他版本安装 构建工具(参考工具部署方式) 一.环境整合 构 ...

  8. linux wget命令的重要用法:下载文件并保存,后台下载

    Linux wget命令是一个下载文件的工具,它用在命令行下. #从网络下载一个文件并保存在当前目录 [root@node5 ~]# wget http://cn.wordpress.org/word ...

  9. C# Log4net 组件无法写日志 IsDebuged、IsInfoEnabled、IsErrorEnabled 全部为false

    [assembly: log4net.Config.XmlConfigurator(ConfigFile = "Log4Net.config", Watch = true)] 如果 ...

  10. C#的奇技淫巧:利用WinRM来远程操控其他服务器上的进程

      前言:有时候远程服务器的进程你想偷偷去围观一下有哪些,或者对一些比较调皮的进程进行封杀,或者对一些自己研发的服务进行远程手动启动或者重启等,又不想打开远程桌面,只想悄咪咪地执行,那也许下面的文章会 ...