HttpClient发送https请求,信任所有证书

客户端向服务器发送https请求时,会验证服务端的证书状态,可以设置信任所有证书,绕过这一步。

查看HttpClient官方文档,示例如下:

使用SSLContextBuilder来创建SSLContext实例,该类的方法如下:

//参数为信任的证书,信任策略 
public SSLContextBuilder loadTrustMaterial(KeyStore truststore, TrustStrategy trustStrategy) throws NoSuchAlgorithmException, KeyStoreException {
        TrustManagerFactory tmfactory = TrustManagerFactory.getInstance(this.trustManagerFactoryAlgorithm == null ? TrustManagerFactory.getDefaultAlgorithm() : this.trustManagerFactoryAlgorithm);
        tmfactory.init(truststore);
        TrustManager[] tms = tmfactory.getTrustManagers();
        if (tms != null) {
            if (trustStrategy != null) {
                for(int i = 0; i < tms.length; ++i) {
                    TrustManager tm = tms[i];
                    if (tm instanceof X509TrustManager) {
                        tms[i] = new SSLContextBuilder.TrustManagerDelegate((X509TrustManager)tm, trustStrategy);
                    }
                }
            }

            TrustManager[] arr$ = tms;
            int len$ = tms.length;

            for(int i$ = 0; i$ < len$; ++i$) {
                TrustManager tm = arr$[i$];
                this.trustManagers.add(tm);
            }
        }

        return this;
    }
    //重载的方法,不需要证书,只需要信任策略
    public SSLContextBuilder loadTrustMaterial(TrustStrategy trustStrategy) throws NoSuchAlgorithmException, KeyStoreException {
        return this.loadTrustMaterial((KeyStore)null, (TrustStrategy)trustStrategy);
    }

首先,要创建httpClient实例,代码如下:

public static CloseableHttpClient createSSLClientDefault() {
        try {
            //使用 loadTrustMaterial() 方法实现一个信任策略,信任所有证书
            SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
                // 信任所有
                public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                    return true;
                }
            }).build();
            //NoopHostnameVerifier类:  作为主机名验证工具,实质上关闭了主机名验证,它接受任何        
            //有效的SSL会话并匹配到目标主机。
            HostnameVerifier hostnameVerifier = NoopHostnameVerifier.INSTANCE;
            SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, hostnameVerifier);
            return HttpClients.custom().setSSLSocketFactory(sslsf).build();
        } catch (KeyManagementException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (KeyStoreException e) {
            e.printStackTrace();
        }
        return HttpClients.createDefault();

    }

之后,就可以用该实例发请求,这里贴一个发送post请求的示例代码:

    /**
     * 模拟发送 post 请求
     */
    public static String doPost(String url, String data) {
        //构建POST请求   请求地址请更换为自己的。
        HttpPost post = new HttpPost(url);
        InputStream inputStream = null;
        String result="";
        try {
            //使用之前写的方法创建httpClient实例
            CloseableHttpClient httpClient = createSSLClientDefault();
            // 构造消息头
            post.setHeader("Content-type", "application/json; charset=utf-8");
            post.setHeader("Connection", "Close");
            // 构建消息实体
            StringEntity entity = new StringEntity(data, Charset.forName("UTF-8"));
            entity.setContentEncoding("UTF-8");
            // 发送Json格式的数据请求
            entity.setContentType("application/json");
            post.setEntity(entity);
            //发送请求
            HttpResponse response = httpClient.execute(post);
            result=getResponseMessage(response);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return result;
    }

 

  • 7
    点赞
  • 52
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
HttpClient是一个用于发送HTTP请求的开源框架,可以通过它发送GET、POST、PUT、DELETE等各种类型的请求。 如果需要使用HttpClient发送HTTPS的POST请求,需要对HttpClient进行配置,以确保安全性。 首先,需要创建一个SSL连接,用于发送HTTPS请求。可以通过创建一个SSL连接工厂来实现,这个工厂会使用信任的CA证书来验证目标服务器的身份。 接下来,创建一个HttpClient实例,并设置SSL连接工厂。 然后,创建一个HttpPost对象,设置请求的URL和请求参数。 接着,设置请求头,包括标识请求类型为POST、设置Content-Type为application/x-www-form-urlencoded等。 最后,使用HttpClient的execute方法执行POST请求,并获取返回的响应。 下面是一个示例代码: ``` import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.ssl.SSLContextBuilder; import org.apache.http.ssl.TrustStrategy; import org.apache.http.util.EntityUtils; import javax.net.ssl.SSLContext; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; public class HttpsPostExample { public static void main(String[] args) throws Exception { // 创建SSL连接工厂 SSLContext sslContext = SSLContextBuilder.create() .loadTrustMaterial(new TrustStrategy() { public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException { return true; // 所有证书都被信任 } }) .build(); // 创建HttpClient实例,并设置SSL连接工厂 CloseableHttpClient httpClient = HttpClients.custom() .setSSLContext(sslContext) .build(); // 创建HttpPost对象,并设置URL和请求参数 HttpPost httpPost = new HttpPost("https://example.com"); String requestBody = "param1=value1&param2=value2"; httpPost.setEntity(new StringEntity(requestBody)); // 设置请求头 httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded"); // 发送POST请求,并获取响应 CloseableHttpResponse response = httpClient.execute(httpPost); String responseBody = EntityUtils.toString(response.getEntity()); // 输出响应结果 System.out.println(responseBody); // 关闭连接 response.close(); httpClient.close(); } } ``` 以上就是使用HttpClient发送HTTPS的POST请求的方法。通过SSL连接工厂的设置,可以确保请求的安全性。在实际使用中,可以根据需要设置请求参数、请求头等。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值