[Http]跳过SSL认证

本文介绍了一个用于处理HTTPS请求的工具类实现,该类通过Apache HttpClient进行网络请求,支持基本认证,并配置了SSL上下文以处理证书验证,适用于需要安全连接的应用场景。

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

package com.pccw.hktdcb.apiserver.util;

import it.sauronsoftware.base64.Base64;

import java.io.IOException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLException;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.conn.ssl.X509HostnameVerifier;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class HttpsRequestUtil {
	protected static final Logger logger = LoggerFactory
			.getLogger(HttpsRequestUtil.class);
	private static final int TIME_OUT = Integer.parseInt(SystemConfig
			.getProperty("https_client_timeout")) * 1000;

	public static HttpClient getHttpClient() {

		@SuppressWarnings("deprecation")
		HttpClient httpclient = new DefaultHttpClient();
		try {
			// Secure Protocol implementation.
			SSLContext ctx = SSLContext.getInstance("SSL");

			// Implementation of a trust manager for X509 certificates
			X509TrustManager tm = new X509TrustManager() {

				public void checkClientTrusted(X509Certificate[] xcs,
						String string) throws CertificateException {

				}

				public void checkServerTrusted(X509Certificate[] xcs,
						String string) throws CertificateException {
				}

				public X509Certificate[] getAcceptedIssuers() {
					return null;
				}
			};

			X509HostnameVerifier hostnameVerifier = new X509HostnameVerifier() {

				public boolean verify(String hostname, SSLSession session) {
					// TODO Auto-generated method stub
					return true;
				}

				public void verify(String arg0, SSLSocket arg1)
						throws IOException {
					// TODO Auto-generated method stub

				}

				public void verify(String arg0, X509Certificate arg1)
						throws SSLException {
					// TODO Auto-generated method stub

				}

				public void verify(String arg0, String[] arg1, String[] arg2)
						throws SSLException {
					// TODO Auto-generated method stub

				}
			};

			ctx.init(null, new TrustManager[] { tm }, null);
			SSLSocketFactory ssf = new SSLSocketFactory(ctx, hostnameVerifier);

			ClientConnectionManager ccm = httpclient.getConnectionManager();
			// register https protocol in httpclient's scheme registry
			SchemeRegistry sr = ccm.getSchemeRegistry();
			sr.register(new Scheme("https", 443, ssf));
			sr.register(new Scheme("http", 80, PlainSocketFactory
					.getSocketFactory()));

			// set Time out
			httpclient.getParams().setParameter(
					CoreConnectionPNames.CONNECTION_TIMEOUT, TIME_OUT);
			httpclient.getParams().setParameter(
					CoreConnectionPNames.SO_TIMEOUT, TIME_OUT);

		} catch (NoSuchAlgorithmException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (KeyManagementException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return httpclient;

	}

	public static String getHTTPSRequest(String url, String userName,
			String password) {

		logger.info("HttpsRequestUtil : getHTTPSRequest start............");
		logger.debug("url : " + url);
		String result = null;

		HttpGet httpget = new HttpGet(url);
		try {

			String authString = userName + ":" + password;
			String authStringEnc = new String(Base64.encode(authString
					.getBytes()));

			httpget.addHeader("Authorization", "Basic " + authStringEnc);
			httpget.addHeader("content-type", "application/json");
			httpget.addHeader("accept", "application/json");

			HttpClient httpclient = getHttpClient();
			HttpResponse response = httpclient.execute(httpget);
			if (response != null) {
				HttpEntity resEntity = response.getEntity();
				if (resEntity != null) {
					int httpStatus = response.getStatusLine().getStatusCode();
					if (httpStatus == HttpStatus.SC_OK) {
						result = EntityUtils.toString(resEntity, "UTF-8");
					} else {
						logger.error(
								"HttpsRequestUtil : getHTTPSRequest failed,  http status code is [{}]",
								httpStatus);
					}
				}
			}

			logger.debug("HttpsRequestUtil : getHTTPSRequest;result = "
					+ result);

		} catch (ClientProtocolException e) {
			logger.error(
					"HttpsRequestUtil : getHTTPSRequest error occur, Exception is [{}]",
					e.getMessage());
		} catch (IOException e) {
			logger.error(
					"HttpsRequestUtil : getHTTPSRequest error occur, Exception is [{}]",
					e.getMessage());
		} finally {
			httpget.releaseConnection();
		}

		logger.info("HttpsRequestUtil : getHTTPSRequest end........");
		return result;
	}

}

 

### 创建WebSocketContainer并跳过SSL认证 在Java中,`javax.websocket.WebSocketContainer` 是用于管理WebSocket连接的核心接口。要实现跳过SSL认证的功能,可以通过自定义 `javax.net.ssl.SSLContext` 来配置信任所有的证书。 以下是具体的实现方式: #### 自定义SSL上下文以跳过SSL验证 通过设置一个不执行任何实际验证的信任管理器来忽略SSL证书验证[^1]。 ```java import javax.net.ssl.*; import java.security.cert.X509Certificate; import javax.websocket.ContainerProvider; import javax.websocket.Session; import javax.websocket.WebSocketContainer; public class WebSocketSslExample { public static void main(String[] args) throws Exception { // 设置默认的 SSL 上下文为信任所有证书 configureSslContext(); // 获取 WebSocket 容器实例 WebSocketContainer container = ContainerProvider.getWebSocketContainer(); // 进行 WebSocket 的连接操作... Session session = container.connectToServer( YourEndpointClass.class, URI.create("wss://your-websocket-url.com/endpoint") ); } private static void configureSslContext() throws Exception { TrustManager[] trustAllCerts = new TrustManager[]{ new X509TrustManager() { @Override public X509Certificate[] getAcceptedIssuers() { return null; } @Override public void checkClientTrusted(X509Certificate[] certs, String authType) {} @Override public void checkServerTrusted(X509Certificate[] certs, String authType) {} } }; SSLContext sc = SSLContext.getInstance("TLS"); sc.init(null, trustAllCerts, new java.security.SecureRandom()); HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); // 忽略主机名验证 HostnameVerifier allHostsValid = (hostname, session) -> true; HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid); } } ``` 上述代码实现了以下功能: - 使用了一个自定义的 `X509TrustManager` 实现类,该类不会抛出异常从而绕过了服务器端证书的有效性检查。 - 初始化了 `SSLContext` 并将其应用到全局 HTTPS URL 连接上。 - 同时设置了 `HostnameVerifier` 以忽略主机名匹配验证[^2]。 注意:此方法仅适用于开发环境或测试场景,在生产环境中应始终使用有效的SSL/TLS证书来进行安全通信。 #### 关键点说明 - **安全性警告**:跳过SSL认证会使得应用程序容易受到中间人攻击(MitM),因此这种做法只适合于调试或者内部网络中的非敏感数据传输场合[^3]。 - 如果需要更高级别的控制,则可以加载特定CA根证书而不是完全禁用验证逻辑。 --- ###
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值