java ssl client_理解apache httpclient(java)中的ssl

/**

* This example demonstrates how to create secure connections with a custom SSL

* context.

*/

public class ClientCustomSSL {

public final static void main(String[] args) throws Exception {

// Trust own CA and all self-signed certs

SSLContext sslcontext = SSLContexts.custom()

.loadTrustMaterial(new File("my.keystore"), "nopassword".toCharArray(),

new TrustSelfSignedStrategy())

.build();

// Allow TLSv1 protocol only

SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(

sslcontext,

new String[] { "TLSv1" },

null,

SSLConnectionSocketFactory.getDefaultHostnameVerifier());

CloseableHttpClient httpclient = HttpClients.custom()

.setSSLSocketFactory(sslsf)

.build();

try {

HttpGet httpget = new HttpGet("https://httpbin.org/");

System.out.println("Executing request " + httpget.getRequestLine());

CloseableHttpResponse response = httpclient.execute(httpget);

try {

HttpEntity entity = response.getEntity();

System.out.println("----------------------------------------");

System.out.println(response.getStatusLine());

EntityUtils.consume(entity);

} finally {

response.close();

}

} finally {

httpclient.close();

}

}

}

为什么我们需要那个?我已经测试了一个httpclient请求,上面没有任何ssl的东西,并且从https url得到了正确的响应,没有错误。

如果我不添加任何sslcontext,会有什么问题?

如果让它更安全很重要,这条线是什么?以下内容:

.loadTrustMaterial(new File("my.keystore"), "nopassword".toCharArray(),

好像我们需要一些文件和密码?

Java可以使用Apache HttpClient库来发送HTTP请求,包括GET、POST等方式,也可以通过HttpClient库发送HTTPS请求。使用HttpClient发送HTTPS请求需要添加SSL证书和设置SSL连接的相关参数。 以下是通过HttpClient库发送GET、POST请求的示例代码: 1. 发送GET请求 ```java import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; public class HttpClientTest { public static void main(String[] args) throws Exception { CloseableHttpClient httpClient = HttpClients.createDefault(); String url = "http://www.example.com/api?param1=value1&param2=value2"; HttpGet httpGet = new HttpGet(url); String response = null; try (CloseableHttpResponse httpResponse = httpClient.execute(httpGet)) { response = EntityUtils.toString(httpResponse.getEntity()); } System.out.println(response); } } ``` 2. 发送POST请求 ```java 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.util.EntityUtils; public class HttpClientTest { public static void main(String[] args) throws Exception { CloseableHttpClient httpClient = HttpClients.createDefault(); String url = "http://www.example.com/api"; HttpPost httpPost = new HttpPost(url); httpPost.setHeader("Content-Type", "application/json;charset=UTF-8"); String requestBody = "{\"param1\":\"value1\",\"param2\":\"value2\"}"; httpPost.setEntity(new StringEntity(requestBody, "UTF-8")); String response = null; try (CloseableHttpResponse httpResponse = httpClient.execute(httpPost)) { response = EntityUtils.toString(httpResponse.getEntity()); } System.out.println(response); } } ``` 如果需要发送HTTPS请求,则需要添加SSL证书和设置SSL连接的相关参数。具体可以参考以下示例代码: ```java import org.apache.http.client.config.RequestConfig; import org.apache.http.client.methods.HttpGet; import org.apache.http.config.Registry; import org.apache.http.config.RegistryBuilder; import org.apache.http.conn.socket.ConnectionSocketFactory; import org.apache.http.conn.socket.PlainConnectionSocketFactory; import org.apache.http.conn.ssl.SSLConnectionSocketFactory; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.apache.http.ssl.SSLContexts; import org.apache.http.ssl.TrustStrategy; import org.apache.http.util.EntityUtils; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSession; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; public class HttpClientTest { public static void main(String[] args) throws Exception { SSLContext sslContext = SSLContexts.custom() .loadTrustMaterial(null, new TrustStrategy() { @Override public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException { return true; } }).build(); HostnameVerifier hostnameVerifier = new HostnameVerifier() { @Override public boolean verify(String hostname, SSLSession session) { return true; } }; SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext, hostnameVerifier); Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create() .register("https", sslSocketFactory) .register("http", new PlainConnectionSocketFactory()) .build(); PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry); connectionManager.setMaxTotal(200); connectionManager.setDefaultMaxPerRoute(20); RequestConfig requestConfig = RequestConfig.custom() .setSocketTimeout(5000) .setConnectTimeout(5000) .setConnectionRequestTimeout(5000) .build(); CloseableHttpClient httpClient = HttpClients.custom() .setConnectionManager(connectionManager) .setDefaultRequestConfig(requestConfig) .build(); String url = "https://www.example.com/api?param1=value1&param2=value2"; HttpGet httpGet = new HttpGet(url); String response = null; try (CloseableHttpResponse httpResponse = httpClient.execute(httpGet)) { response = EntityUtils.toString(httpResponse.getEntity()); } System.out.println(response); } } ``` 需要注意的是,以上代码SSL证书验证方式为信任所有证书,不建议在生产环境使用。建议根据实际情况设置合适的证书验证方式。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值