HttpClient请求https url时 ssl exception

本文介绍了在使用Android HttpClient请求HTTPS URL时遇到的SSL证书验证失败问题及其解决方案。主要原因是客户端与服务器使用的证书不匹配。提供了两种解决思路:一是使客户端信任所有证书,二是为服务器端添加特定证书。并给出了具体代码实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

最近在使用HttpClient请求https url 时,遇到以下问题:

javax.net.ssl.SSLPeerUnverifiedException: No peer certificate

搜索分析之后,得到原因如下:

Android证书库里带着startssl ca证书,而服务器的Web容器中没有带startssl ca证书,这样Android客户端访问该Web容器发布出来的https url时,
校验就会失败。

解决方式:
1.客户端相信所有证书;
2.为服务器端Web容器添加startssl ca证书;

我的解决方式采取第1种。

实现代码:

public static class TrustAllSSLSocketFactory extends SSLSocketFactory {

		SSLContext sslContext = SSLContext.getInstance("TLS");

		public TrustAllSSLSocketFactory(KeyStore truststore)
				throws NoSuchAlgorithmException, KeyManagementException,
				KeyStoreException, UnrecoverableKeyException {
			super(truststore);

			TrustManager tm = new X509TrustManager() {
				public java.security.cert.X509Certificate[] getAcceptedIssuers() {
					return null;
				}

				@Override
				public void checkClientTrusted(
						java.security.cert.X509Certificate[] chain,
						String authType)
						throws java.security.cert.CertificateException {
				}

				@Override
				public void checkServerTrusted(
						java.security.cert.X509Certificate[] chain,
						String authType)
						throws java.security.cert.CertificateException {
				}
			};

			sslContext.init(null, new TrustManager[] { tm }, null);
		}

		@Override
		public Socket createSocket(Socket socket, String host, int port,
				boolean autoClose) throws IOException, UnknownHostException {
			return sslContext.getSocketFactory().createSocket(socket, host,
					port, autoClose);
		}

		@Override
		public Socket createSocket() throws IOException {
			return sslContext.getSocketFactory().createSocket();
		}
	}
private static SSLSocketFactory getSSLSocketFactory() {
		try {
			KeyStore trustStore = KeyStore.getInstance(KeyStore
					.getDefaultType());

			trustStore.load(null, null);

			SSLSocketFactory sslSocketFactory = new TrustAllSSLSocketFactory(
					trustStore);
			sslSocketFactory
					.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

			return sslSocketFactory;
		}
		catch (Exception e) {
			e.printStackTrace();
		}

		return null;
	}
// 支持http和https两种模式
			SchemeRegistry schReg = new SchemeRegistry();
			schReg.register(new Scheme("http", PlainSocketFactory
					.getSocketFactory(), 80));
			schReg.register(new Scheme("https", getSSLSocketFactory(), 443));

			// 使用线程安全的连接管理来创建HttpClient
			ClientConnectionManager conMgr = new ThreadSafeClientConnManager(
					params, schReg);
PS:如果请求网络使用HttpURLConnection,实现方式也是一样,让客户端信任所有证书。

转载于:https://my.oschina.net/liucundong/blog/173162

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、付费专栏及课程。

余额充值