Java如何实现通过证书访问Https请求
作者:王绍桦 时间:2021-10-19 08:51:36
Java通过证书访问Https请求
创建证书管理器类
import java.io.FileInputStream;
import java.security.KeyStore;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509TrustManager;
public class MyX509TrustManager implements X509TrustManager{
X509TrustManager sunJSSEX509TrustManager;
MyX509TrustManager(String keystoreFile,String pass) throws Exception {
KeyStore ks = KeyStore.getInstance("JKS");
ks.load(new FileInputStream(keystoreFile), pass.toCharArray());
TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509", "SunJSSE");
tmf.init(ks);
TrustManager tms [] = tmf.getTrustManagers();
for (int i = 0; i < tms.length; i++) {
if (tms[i] instanceof X509TrustManager) {
sunJSSEX509TrustManager = (X509TrustManager) tms[i];
return;
}
}
throw new Exception("Couldn't initialize");
}
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
try {
sunJSSEX509TrustManager.checkClientTrusted(chain, authType);
} catch (CertificateException excep) {
excep.printStackTrace();
}
}
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
try {
sunJSSEX509TrustManager.checkServerTrusted(chain, authType);
} catch (CertificateException excep) {
excep.printStackTrace();
}
}
@Override
public X509Certificate[] getAcceptedIssuers() {
return sunJSSEX509TrustManager.getAcceptedIssuers();
}
}
调用测试
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.URL;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
public class HttpsCaTest {
public static void main(String[] args) throws Exception {
String keystoreFile = "D:\\tomcat.keystore";
String keystorePass = "ldysjhj";
//设置可通过ip地址访问https请求
HttpsURLConnection.setDefaultHostnameVerifier(new NullHostNameVerifier());
// 创建SSLContext对象,并使用我们指定的信任管理器初始化
TrustManager[] tm = { new MyX509TrustManager(keystoreFile,keystorePass) };
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, tm, new java.security.SecureRandom());
// 从上述SSLContext对象中得到SSLSocketFactory对象
SSLSocketFactory ssf = sslContext.getSocketFactory();
String urlStr = "https://192.168.1.10/login_queryLkBySfmc.htm";
URL url = new URL(urlStr);
HttpsURLConnection con = (HttpsURLConnection) url.openConnection();
con.setSSLSocketFactory(ssf);
con.setRequestMethod("POST"); // 设置以POST方式提交数据
con.setDoInput(true); // 打开输入流,以便从服务器获取数据
con.setDoOutput(true);// 打开输出流,以便向服务器提交数据
//设置发送参数
String param = "sfmc=测试";
PrintWriter out = new PrintWriter(new OutputStreamWriter(con.getOutputStream(),"UTF-8"));
out.print(param);
out.flush();
out.close();
//读取请求返回值
InputStreamReader in = new InputStreamReader(con.getInputStream(),"UTF-8");
BufferedReader bfreader = new BufferedReader(in);
String result = "";
String line = "";
while ((line = bfreader.readLine()) != null) {
result += line;
}
System.out.println("result:"+result);
}
}
工具类
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLSession;
public class NullHostNameVerifier implements HostnameVerifier{
@Override
public boolean verify(String hostname, SSLSession session) {
return true;
}
}
https请求绕过证书检测
import org.apache.http.HttpEntity;
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.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.util.EntityUtils;
import javax.net.ssl.SSLContext;
public class HttpsClientUtil {
private static CloseableHttpClient httpClient;
static {
try {
SSLContext sslContext = SSLContextBuilder.create().useProtocol(SSLConnectionSocketFactory.SSL).loadTrustMaterial((x, y) -> true).build();
RequestConfig config = RequestConfig.custom().setConnectTimeout(5000).setSocketTimeout(5000).build();
httpClient = HttpClientBuilder.create().setDefaultRequestConfig(config).setSSLContext(sslContext).setSSLHostnameVerifier((x, y) -> true).build();
} catch (Exception e) {
e.printStackTrace();
}
}
public String doPost(String url, String jsonString) {
try {
HttpPost httpPost = new HttpPost(url);
StringEntity stringEntity = new StringEntity(jsonString, "utf-8");
stringEntity.setContentType("application/json");
httpPost.setEntity(stringEntity);
CloseableHttpResponse response = httpClient.execute(httpPost);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != 200) {
httpPost.abort();
throw new RuntimeException("HttpClient,error status code :"
+ statusCode);
}
HttpEntity entity = response.getEntity();
String result = null;
if (entity != null) {
result = EntityUtils.toString(entity, "utf-8");
}
EntityUtils.consume(entity);
response.close();
return result;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
来源:https://blog.csdn.net/rexueqingchun/article/details/86686885
标签:Java,证书,访问,Https
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
Java Springboot如何基于图片生成下载链接
2023-05-19 19:57:32
Java Web实现文件下载和乱码处理方法
2022-03-14 20:28:38
解决Android Studio xml 格式化不自动换行的问题
2021-09-10 06:15:42
![](https://img.aspxhome.com/file/2023/9/88669_0s.jpg)
Springboot通过谷歌Kaptcha 组件生成图形验证码功能
2021-07-24 23:42:47
![](https://img.aspxhome.com/file/2023/9/69659_0s.png)
详解spring-boot actuator(监控)配置和使用
2022-07-12 17:20:37
Java设计模式之迭代模式(Iterator模式)介绍
2022-07-24 16:03:29
浅谈对象数组或list排序及Collections排序原理
2021-10-18 08:35:31
Java Vector和ArrayList的异同分析及实例讲解
2023-12-03 17:27:10
Java可变个数形参的方法实例代码
2023-01-15 18:35:56
![](https://img.aspxhome.com/file/2023/2/62372_0s.png)
Java获取控制台输入的两种方法小结
2023-11-29 12:40:44
Java SpringBoot高级用法详解
2021-07-03 18:27:09
![](https://img.aspxhome.com/file/2023/8/62998_0s.png)
Spring Boot 实现图片上传并回显功能
2021-10-11 17:45:20
![](https://img.aspxhome.com/file/2023/6/68776_0s.png)
UnityShader使用图像叠加实现运动模糊
2021-09-24 14:45:16
![](https://img.aspxhome.com/file/2023/7/94647_0s.jpg)
Java程序常见异常及处理汇总
2021-08-12 04:20:44
![](https://img.aspxhome.com/file/2023/8/66688_0s.jpg)
Java多线程 线程组原理及实例详解
2022-11-26 02:51:40
![](https://img.aspxhome.com/file/2023/5/85535_0s.png)
android实现手机截屏并保存截图功能
2022-07-16 01:47:46
![](https://img.aspxhome.com/file/2023/4/87534_0s.jpg)
SpringBoot 如何实现异步编程
2023-04-15 13:45:43
Unity3D实现旋钮控制灯光效果
2021-09-05 21:16:58
LINQ基础之Intersect、Except和Distinct子句
2022-01-19 00:46:13
详解Spring整合Ehcache管理缓存
2022-02-10 00:50:17