使用个人p12证书请求https接口数据

依赖

java 复制代码
		<dependency>
			<groupId>org.apache.httpcomponents</groupId>
			<artifactId>httpclient</artifactId>
			<version>4.5.3</version>
		</dependency>

code

java 复制代码
package com.hexin.cbas.test;

import org.apache.commons.net.util.TrustManagerUtils;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.security.KeyStore;

public class Https2Test {


    private final static String PFX_PATH = "D:\\person_client.p12";
    private final static String PFX_PWD = "pwd"; //客户端证书密码及密钥库密码

    public static String sslRequestGet(String url) throws Exception {
        KeyStore keyStore = KeyStore.getInstance("PKCS12");
        try (InputStream stream = Files.newInputStream(Paths.get(PFX_PATH))){
            // 这里就指的是KeyStore库的密码
            keyStore.load(stream, PFX_PWD.toCharArray());
        }
        KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        keyManagerFactory.init(keyStore, PFX_PWD.toCharArray());
        SSLContext sslContext = SSLContext.getInstance("TLS");
        TrustManager[] trustManagers = new TrustManager[] {TrustManagerUtils.getAcceptAllTrustManager()};
        sslContext.init(keyManagerFactory.getKeyManagers(), trustManagers, null);
        HttpGet httpget = new HttpGet(url);
        try (CloseableHttpClient httpclient = HttpClients.custom().setSSLContext(sslContext)
                .setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE).build();
             CloseableHttpResponse response = httpclient.execute(httpget)){
            // 返回结果
            return EntityUtils.toString(response.getEntity(), "UTF-8");
        }
    }
    public static void main(String[] args) throws Exception {
        //url使用的是域名是需要设置,否则会报handshake alert:  unrecognized_name错误
        System.setProperty("jsse.enableSNIExtension", "false");
        System.out.println(sslRequestGet("https://xxxxx.com/user/get"));
    }
}
相关推荐
言成言成啊2 小时前
TCP与UDP的端口连通性
网络协议·tcp/ip·udp
敲代码娶不了六花2 小时前
对计算机网络中“层”的理解
网络·网络协议·tcp/ip·计算机网络
低调之人2 小时前
Fiddler勾选https后google浏览器网页访问不可用
前端·测试工具·https·fiddler·hsts
x66ccff3 小时前
HTTPS如何通过CA证书实现安全通信,以及HTTPS的局限性
网络协议·安全·https
Graceful_scenery3 小时前
https双向认证
服务器·网络·网络协议·http·https
幽弥千月7 小时前
【ELK】ES单节点升级为集群并开启https【亲测可用】
elk·elasticsearch·https
njnu@liyong14 小时前
图解HTTP-HTTP状态码
网络协议·计算机网络·http
王三三15 小时前
群晖利用acme.sh自动申请证书并且自动重载证书的问题解决
linux·自动化·证书·群晖·acme·acme.sh·lets encrypt
代码洁癖症患者16 小时前
HTTP请求的奇幻旅程:从发起至响应的全方位探索
网络·网络协议·http
岳不谢17 小时前
华为DHCP高级配置学习笔记
网络·笔记·网络协议·学习·华为