自学内容网 自学内容网

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

依赖

<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.3</version>
</dependency>

code

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"));
    }
}



原文地址:https://blog.csdn.net/qq_34075559/article/details/140401110

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!