概述
日常上传、下载文件时可能有不需要验证证书的场景,比如证书过期、不正确之类的也可以正常的上传下载文件。
Java中使用https协议时,是通过X.509证书进行校验的。
首先我们先了解下什么是X.509证书。
什么是X.509证书
X.509是公钥基础设施(PKI:Public Key Infrastructure)的标准格式,其实就是一种证书的标准格式,规定证书是什么样的。
X.509证书就是基于国际电线联盟(ITU)制定的X.509标准的数字证书。
X.509证书主要用于识别互联网通信和计算机网络中的身份,保护数据传输安全。X.509证书无处不在,比如我们每天使用的网站、移动应用程序、电子文档以及连接的设备等都有它的身影。
X.509证书的结构优势在于它是由公钥和私钥组成的密钥对而构建的。公钥和私钥能够用于加密和解密信息,验证发送者的身份和确保信息本身的安全性。基于X.509的PKI最常见的用例是使用SSL证书让网站与用户之间实现HTTPS安全浏览。X.509协议统一也使用于应用程序安全的代码签名、数字签名和其他重要的互联网协议。
证书校验引发的问题
javax.net.ssl.SSLException: hostname in certificate didn’t match
含义就是说现在程序运行的域名,与请求的证书不一致,不匹配导致的。那么解决方案必定是把证书忽略了,也就是不验证证书的情况下请求上游信息了。
java HttpsURLConnection忽略证书
HttpURLConnection是java的标准类,没有做封装,用起来比较原始,HttpURLConnection通常可以访问http/https协议,但是如果想忽略证书校验的话,需要使用HttpsURLConnection访问url,同时HttpsURLConnection只能访问https的协议。如果使用java原生的标准类访问url,对于Https的连接可以根据协议类型判断到底是使用HttpURLConnection还是HttpsURLConnection。
下面是HttpURLConnection和HttpURLConnection忽略证书访问的示例。
import com.alibaba.fastjson.JSONObject;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
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;
/**
* @Description : java原生客户端忽略证书
* @Version : V1.0.0
* @Date : 2023/1/3 11:38
*/
public class JavaHttpUtil {
/**
* 发送https请求
*
* @param url url
* @param requestMethod 请求方式
* @param param 请求参数
* @return 返回值
*/
public String sendHttpsRequest(String url, String requestMethod, String param) {
StringBuilder result = new StringBuilder();
try {
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, new TrustManager[]{
new X509TrustManager() {
@Override
public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
}
@Override
public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
}
@Override
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
}
}
}, new SecureRandom());
URL console = new URL(url);
HttpsURLConnection conn = (HttpsURLConnection) console.openConnection();
// GET/POST
conn.setRequestMethod(requestMethod);
conn.setRequestProperty("Content-Type", "application/json");
conn.setDoOutput(true);
conn.setDoInput(true);
if (null != param) {
OutputStream outputStream = conn.getOutputStream();
// 注意编码格式
outputStream.write(param.getBytes("UTF-8"));
outputStream.close();
}
// 设置证书忽略相关操作
conn.setSSLSocketFactory(sc.getSocketFactory());
conn.setHostnameVerifier(new HostnameVerifier() {
@Override
public boolean verify(String s, SSLSession sslSession) {
return true;
}
});
conn.connect();
InputStream is = conn.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String ret = "";
while ((ret = br.readLine()) != null) {
if (ret != null && !ret.trim().equals("")) {
result.append(new String(ret.getBytes("utf-8"), "utf-8"));
}
}
conn.disconnect();
br.close();
} catch (NoSuchAlgorithmException | KeyManagementException | MalformedURLException e) {
e.printStackTrace();
} catch (IOException ioException) {
ioException.printStackTrace();
}
return result.toString();
}
// http协议访问方法
public String sendHttpRequest(String url, String requestMethod, String param) {
StringBuilder result = new StringBuilder();
try {
URL console = new URL(url);
HttpURLConnection conn = (HttpURLConnection) console.openConnection();
// GET/POST
conn.setRequestMethod(requestMethod);
conn.setRequestProperty("Content-Type", "application/json");
conn.setDoOutput(true);
conn.setDoInput(true);
if (null != param) {
OutputStream outputStream = conn.getOutputStream();
// 注意编码格式
outputStream.write(param.getBytes("UTF-8"));
outputStream.close();
}
conn.connect();
InputStream is = conn.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String ret = "";
while ((ret = br.readLine()) != null) {
if (ret != null && !ret.trim().equals("")) {
result.append(new String(ret.getBytes("utf-8"), "utf-8"));
}
}
conn.disconnect();
br.close();
} catch (IOException ioException) {
ioException.printStackTrace();
}
return result.toString();
}
public static void main(String[] args) {
final JavaHttpUtil javaHttpUtil = new JavaHttpUtil();
JSONObject js = new JSONObject();
js.put("user", "xioamin");
js.put("ip", "127.0.0.1");
final String result = javaHttpUtil.sendHttpRequest("https://abc.test:5808/getToken", "POST", js.toString());
System.out.println(result);
final String get = javaHttpUtil.sendHttpsRequest("https://www.baidu.com/", "GET", null);
System.out.println(get);
}
}
org.apache.httpcomponents httpclient客户端忽略证书方法
HttpClient和httpurlconnection介绍
HttpClient是Apache开源组织提供的一个Http客户端,HttpClient封装了Session、Cookie等细节问题的处理。简单来说,HttpClient就是一个增强版的HttpURLConnection,HttpURLConnection可以做的事情 HttpClient全部可以做;HttpURLConnection没有提供的有些功能,HttpClient也提供了,但它只是关注于如何发送请求、接收响应,以及管理HTTP连接。文章来源:https://www.toymoban.com/news/detail-787559.html
忽略证书示例
package com.practice.httputils.trustallcerts;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.HttpException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.config.SocketConfig;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.client.StandardHttpRequestRetryHandler;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.protocol.HTTP;
import org.apache.http.ssl.SSLContexts;
import org.apache.http.util.EntityUtils;
import javax.net.ssl.SSLContext;
import java.io.IOException;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Map;
import java.util.Objects;
/**
* @Description : httpComponents httpclient工具
* @Version : V1.0.0
* @Date : 2023/1/3 17:46
*/
public class HttpClientUtil {
/**
* 忽视所有证书验证-使用org.apache.httpcomponents 4.5版本
*
* @return
*/
public static CloseableHttpClient trustAllCertsHttpClient() throws NoSuchAlgorithmException, KeyStoreException, KeyManagementException {
SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, new TrustStrategy() {
// 忽略证书校验
@Override
public boolean isTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
return true;
}
}).build();
SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContext, new String[]{"TLSv1.2"}, null, NoopHostnameVerifier.INSTANCE);
final Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
.register("http", PlainConnectionSocketFactory.getSocketFactory())
.register("https", sslConnectionSocketFactory).build();
// 5秒超时
RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(5000)
.setSocketTimeout(10000).setConnectTimeout(10000).build();
SocketConfig socketConfig = SocketConfig.custom().setSoTimeout(5000).build();
PoolingHttpClientConnectionManager cm =
new PoolingHttpClientConnectionManager(socketFactoryRegistry);
cm.setMaxTotal(300);
// 单路由最大并发数
cm.setDefaultMaxPerRoute(30);
return HttpClients.custom()
.setDefaultRequestConfig(requestConfig)
.setRetryHandler(new StandardHttpRequestRetryHandler())
.setDefaultSocketConfig(socketConfig).setConnectionManager(cm).build();
}
private static String sendPostHttpRequestWithTimeOut(String reqURL, String param, Map<String, String> headerMap, int readTimeout) throws HttpException {
String result = "-1";
HttpPost httpPost = new HttpPost(reqURL);
httpPost.setHeader(HTTP.CONTENT_TYPE, "application/json; charset=" + "UTF-8");
CloseableHttpResponse response = null;
try {
if (param != null) {
StringEntity entity = new StringEntity(param, "UTF-8");
httpPost.setEntity(entity);
if (!Objects.isNull(headerMap) && headerMap.size() != 0) {
for (Map.Entry<String, String> entry : headerMap.entrySet()) {
httpPost.addHeader(entry.getKey(), entry.getValue());
}
}
}
RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(3000).setConnectTimeout(4000)
.setSocketTimeout(readTimeout).build();
httpPost.setConfig(requestConfig);
response = trustAllCertsHttpClient().execute(httpPost, HttpClientContext.create());
HttpEntity entity = response.getEntity();
if (null != entity) {
result = EntityUtils.toString(entity, ContentType.getOrDefault(entity).getCharset());
EntityUtils.consume(entity);
}
} catch (Exception e) {
throw new HttpException("请求通信[" + reqURL + "]时读取超时,堆栈轨迹如下:", e);
} finally {
if (response != null) {
try {
response.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (httpPost != null) {
httpPost.releaseConnection();
}
}
return result;
}
public static void main(String[] args) throws HttpException {
JSONObject js = new JSONObject();
js.put("user", "aaa");
js.put("ip", "127.0.0.1");
final String result = sendPostHttpRequestWithTimeOut("http://aaatest:5015/getToken", js.toString(), null, 3000);
System.out.println(result);
final String get = sendPostHttpRequestWithTimeOut("https://www.baidu.com/", null, null, 1000);
System.out.println(get);
}
}
参考
什么是X.509证书?X.509证书工作原理及应用?
java忽略证书验证(兼容http,https)进行get/post请求–使用(org.apache.httpcomponents httpclient客户端)
httpurlconnection 访问https
java忽略证书验证(兼容http,https)进行get/post请求–使用(org.apache.httpcomponents httpclient客户端)文章来源地址https://www.toymoban.com/news/detail-787559.html
到了这里,关于java忽略证书验证(兼容http,https)的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!