Java HttpClient如何带证书发起请求

javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
	at sun.security.ssl.Alerts.getSSLException(Alerts.java:192)
	at sun.security.ssl.SSLSocketImpl.fatal(SSLSocketImpl.java:1946)
	at sun.security.ssl.Handshaker.fatalSE(Handshaker.java:316)
	at sun.security.ssl.Handshaker.fatalSE(Handshaker.java:310)
	at sun.security.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:1639)
	at sun.security.ssl.ClientHandshaker.processMessage(ClientHandshaker.java:223)
	at sun.security.ssl.Handshaker.processLoop(Handshaker.java:1037)
	at sun.security.ssl.Handshaker.process_record(Handshaker.java:965)
	at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:1064)
	at sun.security.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1367)
	at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1395)
	at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1379)
	at org.apache.http.conn.ssl.SSLConnectionSocketFactory.createLayeredSocket(SSLConnectionSocketFactory.java:394)
	at org.apache.http.conn.ssl.SSLConnectionSocketFactory.connectSocket(SSLConnectionSocketFactory.java:353)
	at org.apache.http.impl.conn.DefaultHttpClientConnectionOperator.connect(DefaultHttpClientConnectionOperator.java:141)
	at org.apache.http.impl.conn.PoolingHttpClientConnectionManager.connect(PoolingHttpClientConnectionManager.java:353)
	at org.apache.http.impl.execchain.MainClientExec.establishRoute(MainClientExec.java:380)
	at org.apache.http.impl.execchain.MainClientExec.execute(MainClientExec.java:236)
	at org.apache.http.impl.execchain.ProtocolExec.execute(ProtocolExec.java:184)
	at org.apache.http.impl.execchain.RetryExec.execute(RetryExec.java:88)
	at org.apache.http.impl.execchain.RedirectExec.execute(RedirectExec.java:110)
	at org.apache.http.impl.client.InternalHttpClient.doExecute(InternalHttpClient.java:184)
	at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:82)
	at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:107)

如果我们在开发中使用HttpClient遇到了上面的错误,说明对方的接口需要特定的证书才能请求,那么如何在HttpClient请求中加入证书呢?
请看下面的代码


import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import java.io.FileInputStream;
import java.security.KeyStore;
import java.security.SecureRandom;

/**
 * @author niudali
 * @date 2021/2/3 11:16
 * @desc
 */

public class HttpUtil {

    private static SSLContext sslContext = null;
    private static HttpClient httpClient = new DefaultHttpClient();
    private static String siteUrl = "";


    private static String KEY_STORE_CLIENT_PATH = "";
    private static String KEY_STORE_TRUST_PATH = "";
    private static String KEY_STORE_PASSWORD = "";


    /**
     * @param _siteUrl
     * @param p12Path .p12文件地址
     * @param trustPath .truststore文件地址
     * @param password 密钥密码
     */
    public static void init(String _siteUrl, String p12Path, String trustPath, String password) {

        try {
            siteUrl = _siteUrl;
            KEY_STORE_CLIENT_PATH = p12Path;
            KEY_STORE_TRUST_PATH = trustPath;
            KEY_STORE_PASSWORD = password;
            //设置环境变量
            System.setProperty("javax.net.ssl.keyStore", KEY_STORE_CLIENT_PATH);
            System.setProperty("javax.net.ssl.keyStorePassword", KEY_STORE_PASSWORD);
            System.setProperty("javax.net.ssl.keyStoreType", "PKCS12");
            System.setProperty("javax.net.ssl.trustStore", KEY_STORE_TRUST_PATH);
            System.setProperty("javax.net.ssl.trustStorePassword", KEY_STORE_PASSWORD);
            System.setProperty("javax.net.ssl.trustStoreType", "jks");
            KeyStore kstore = KeyStore.getInstance("PKCS12");
            kstore.load(new FileInputStream(KEY_STORE_CLIENT_PATH), KEY_STORE_PASSWORD.toCharArray());
            KeyManagerFactory keyFactory = KeyManagerFactory.getInstance("sunx509");
            keyFactory.init(kstore, KEY_STORE_PASSWORD.toCharArray());
            KeyStore tstore = KeyStore.getInstance("jks");
            tstore.load(new FileInputStream(KEY_STORE_TRUST_PATH), KEY_STORE_PASSWORD.toCharArray());
            TrustManagerFactory tmf = TrustManagerFactory.getInstance("sunx509");
            tmf.init(tstore);
            TrustManager[] tm = tmf.getTrustManagers();
            sslContext = SSLContext.getInstance("SSL");
            sslContext.init(keyFactory.getKeyManagers(), tm, (SecureRandom) null);
        } catch (Exception e) {
            e.printStackTrace();

        }

    }
    public static String httpPost(String url, String jsonParam) {
        try {
            httpClient = new DefaultHttpClient();
            SSLSocketFactory socketFactory = new SSLSocketFactory(sslContext);
            Scheme sch = new Scheme("https", 443, socketFactory);
            httpClient.getConnectionManager().getSchemeRegistry().register(sch);
            HttpPost httpPost = new HttpPost(url);
            httpPost.addHeader("Content-Type", "application/json");
            httpPost.addHeader("charset", "UTF-8");
            httpPost.setEntity(new StringEntity(jsonParam.toString(), "UTF-8"));
            HttpResponse response = httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                String result = EntityUtils.toString(entity);
                return result;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return "";
    }

}

  • 0
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
要使用Java HttpClient发起请求,你可以按照以下步骤进行操作: 1. 首先,创建一个HttpPost对象,将请求的URL作为参数传递给它。可以使用引用中的示例代码中的以下行完成此步骤: ``` HttpPost httpPost = new HttpPost(url); ``` 2. 接下来,创建一个CloseableHttpClient对象,可以使用引用中的示例代码中的以下行完成此步骤: ``` CloseableHttpClient httpClient = HttpClientBuilder.create().build(); ``` 3. 设置请求的数据格式和内容。你可以使用StringEntity类创建一个包含请求数据的实体。可以使用引用中的示例代码中的以下行完成此步骤: ``` StringEntity entity = new StringEntity(jsonData, "utf-8"); entity.setContentEncoding("UTF-8"); entity.setContentType("application/json"); httpPost.setEntity(entity); ``` 4. 执行POST请求并获取响应结果。可以使用httpClient的execute方法来执行请求,并使用HttpResponse对象接收响应结果。你可以根据需要使用不同的方法来处理响应结果。例如,可以使用BasicResponseHandler类的实例来处理响应结果字符串。可以使用引用中的示例代码中的以下行完成此步骤: ``` BasicResponseHandler handler = new BasicResponseHandler(); result = httpClient.execute(httpPost, handler); ``` 5. 最后,记得释放连接。可以使用httpClient的close方法来关闭连接。可以使用引用中的示例代码中的以下行完成此步骤: ``` httpClient.close(); ``` 综上所述,以上步骤提供了一个示例的Java HttpClient发起请求的过程。根据你的需求,你还可以根据具体的情况进行适当的调整和扩展。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值