java 使用apache httpClient客户端将发布数据发送到https而不使用ssl证书验证

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java 使用apache httpClient客户端将发布数据发送到https而不使用ssl证书验证相关的知识,希望对你有一定的参考价值。

public String sendPost(final String request, final String postData) throws ClientProtocolException, IOException, NoSuchAlgorithmException, KeyManagementException  {
    String result = null;
    SSLContext sslContext = SSLContext.getInstance("SSL");

    // set up a TrustManager that trusts everything
    sslContext.init(null, new TrustManager[] { new X509TrustManager() {
                public X509Certificate[] getAcceptedIssuers() {
                        System.out.println("getAcceptedIssuers =============");
                        return null;
                }

                public void checkClientTrusted(X509Certificate[] certs,
                                String authType) {
                        System.out.println("checkClientTrusted =============");
                }

                public void checkServerTrusted(X509Certificate[] certs,
                                String authType) {
                        System.out.println("checkServerTrusted =============");
                }
    } }, new SecureRandom());

    CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(new SSLSocketFactory(sslContext)).build();
    HttpPost httpPost = new HttpPost(request);
    ByteArrayEntity postDataEntity = new ByteArrayEntity(postData.getBytes());
    httpPost.setEntity(postDataEntity);
    CloseableHttpResponse response = httpclient.execute(httpPost);
    try {
        HttpEntity entity = response.getEntity();
        result = EntityUtils.toString(entity);
        EntityUtils.consume(entity);
    } finally {
        response.close();
    }
    return result;

}

以上是关于java 使用apache httpClient客户端将发布数据发送到https而不使用ssl证书验证的主要内容,如果未能解决你的问题,请参考以下文章

Java使用HttpClient实现Post请求

Java中的httpclient4.5应该怎么使用?

Java之使用HttpClient发送GET请求

Apache HTTPClient依赖问题:POM

Java通过httpclient获取cookie模拟登录

java如何下载和安装org.apache.commons.httpclient的jar包?