使用HttpsURLConnection或httpclient访问https自签名(无效)证书

本文详细介绍使用Java的HttpsURLConnection和HttpClient访问HTTPS服务,并绕过证书验证的过程。通过实例演示了如何配置SSLContext以信任所有证书,以及如何设置连接参数进行GET请求。

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


import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import net.sf.json.JSONObject;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
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.util.EntityUtils;

public class TestMain {

	public static void main(String[] args) {
		// 使用HttpsURLConnection访问https,自签名证书
		TestMain.testHttpUrl();
		// 使用HttpsURLConnection访问https,自签名证书
		// TestMain.testHttpClient();
	}

	/**
	 * ---------------------------------------------------------
	 * 、、、、、、、、、、、使用HttpsURLConnection、、、、、、、、、、、、 開始
	 * ---------------------------------------------------------
	 */
	public static void testHttpUrl() {
		try {

			StringBuffer stringBuffer = new StringBuffer();
			stringBuffer.append("?");
			stringBuffer.append("os=1"); // 操作系统。0=android;1=ios;2=wp
			stringBuffer.append("&");
			stringBuffer.append("osVersion=27"); // 操作系统版本(int)
			stringBuffer.append("&");
			stringBuffer.append("appId=com.XXXX.XXX"); // 应用id
			stringBuffer.append("&");
			stringBuffer.append("appVersion=2&hy_serviceName=XXXAction"); // 应用版本号

			HttpsURLConnection connection = null;
			URL url = new URL(
					"https://172.20.xxx.xxx:443/XXXXX/serviceInvoke"
							+ stringBuffer.toString());


			connection = (HttpsURLConnection) url.openConnection();

			// 设置参数
			connection.setDoOutput(true); // 需要输出
			connection.setDoInput(true); // 需要输入
			connection.setUseCaches(false); // 不允许缓存
			connection.setConnectTimeout(60000); // 设置连接超时
			connection.setReadTimeout(60000); // 设置读取超时
			connection.setRequestMethod("GET"); // 设置POST方式连接

			// 设置请求属性
			connection.setRequestProperty("Content-Type",
					"application/x-www-form-urlencoded");
			connection.setRequestProperty("Connection", "Keep-Alive");// 维持长连接
			connection.setRequestProperty("Accept-Encoding", "gzip");
			connection.setRequestProperty("Charset", "UTF-8");

			// 设置请求头参数
			connection.addRequestProperty("hy_appId", "com.XXX.XXX"); // 设置appId

			HttpsURLConnection https = (HttpsURLConnection) connection;
			SSLSocketFactory oldSocketFactory = TestMain.trustAllHosts(https);
			HostnameVerifier oldHostnameVerifier = https.getHostnameVerifier();
			https.setHostnameVerifier(DO_NOT_VERIFY);

			InputStream in = connection.getInputStream(); // 获取返回数据
			BufferedInputStream bis = new BufferedInputStream(in);
			ByteArrayOutputStream baos = new ByteArrayOutputStream();

			int c;
			while (-1 != (c = bis.read())) {
				baos.write(c);
			}
			bis.close();
			in.close();
			baos.flush();

			byte[] data = baos.toByteArray();
			String responseMsg = new String(data);
			System.out.println(responseMsg);
			org.json.JSONObject jsonObject = new org.json.JSONObject(
					responseMsg);
			org.json.JSONObject content = jsonObject.optJSONObject("content");
			System.out.println(content.toString());
			// System.out.println(new String(responseMsg.getBytes("utf-8"),
			// "gbk") );
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		// 对JSON作解析
	}

	private static SSLSocketFactory trustAllHosts(HttpsURLConnection connection) {
		SSLSocketFactory oldFactory = connection.getSSLSocketFactory();
		try {
			SSLContext sc = SSLContext.getInstance("TLS");
			sc.init(null, trustAllCerts, new java.security.SecureRandom());
			SSLSocketFactory newFactory = sc.getSocketFactory();
			connection.setSSLSocketFactory(newFactory);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return oldFactory;
	}

	private static final TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
		public java.security.cert.X509Certificate[] getAcceptedIssuers() {
			return new java.security.cert.X509Certificate[] {};
		}

		public void checkClientTrusted(X509Certificate[] chain, String authType)
				throws CertificateException {
		}

		public void checkServerTrusted(X509Certificate[] chain, String authType)
				throws CertificateException {
		}
	} };

	private static final HostnameVerifier DO_NOT_VERIFY = new HostnameVerifier() {
		public boolean verify(String hostname, SSLSession session) {
			return true;
		}
	};

	/**
	 * ---------------------------------------------------------
	 * 、、、、、、、、、、、使用HttpsURLConnection、、、、、、、、、、、、 結束
	 * ---------------------------------------------------------
	 */

	/**
	 * ---------------------------------------------------------
	 * 、、、、、、、、、、、使用httpclient、、、、、、、、、、、、 開始
	 * ---------------------------------------------------------
	 */
	public static void testHttpClient() {
		// httpclient get请求,拼接参数
		StringBuffer stringBuffer = new StringBuffer();
		stringBuffer.append("?");
		stringBuffer.append("os=0"); // 操作系统。0=android;1=ios;2=wp
		stringBuffer.append("&");
		stringBuffer.append("osVersion=27"); // 操作系统版本(int)
		stringBuffer.append("&");
		stringBuffer.append("appId=com.XXX.XXX"); // 应用id
		stringBuffer.append("&");
		stringBuffer.append("appVersion=2&hy_serviceName=XXXXXAction"); // 应用版本号
		try {
			String body = "";

			// 采用绕过验证的方式处理https请求
			SSLContext sslcontext = TestMain.createIgnoreVerifySSL();

			// 设置协议http和https对应的处理socket链接工厂的对象
			Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder
					.<ConnectionSocketFactory> create()
					.register("http", PlainConnectionSocketFactory.INSTANCE)
					.register("https",
							new SSLConnectionSocketFactory(sslcontext)).build();
			PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(
					socketFactoryRegistry);
			HttpClients.custom().setConnectionManager(connManager);

			// 创建自定义的httpclient对象
			CloseableHttpClient httpclient = HttpClients.custom()
					.setConnectionManager(connManager).build();

			HttpGet httpPost = new HttpGet(
					"https://220.163.xxx.xxx:7777/XXXXX/serviceInvoke"
							+ stringBuffer.toString());

			// Create a custom response handler
			ResponseHandler<JSONObject> responseHandler = new ResponseHandler<JSONObject>() {
				// 对访问结果进行处理
				public JSONObject handleResponse(final HttpResponse response)
						throws ClientProtocolException, IOException {
					int status = response.getStatusLine().getStatusCode();
					if (status >= 200 && status < 300) {
						HttpEntity entity = response.getEntity();
						if (null != entity) {
							String result = EntityUtils.toString(entity);
							// 根据字符串生成JSON对象
							JSONObject resultObj = JSONObject
									.fromObject(result);
							return resultObj;
						} else {
							return null;
						}
					} else {
						throw new ClientProtocolException(
								"Unexpected response status: " + status);
					}
				}
			};
			// 返回的json对象
			JSONObject responseBody = httpclient.execute(httpPost,
					responseHandler);
			System.out.println(responseBody);
			httpclient.close();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * 绕过验证
	 * 
	 * @return
	 * @throws NoSuchAlgorithmException
	 * @throws KeyManagementException
	 */
	public static SSLContext createIgnoreVerifySSL()
			throws NoSuchAlgorithmException, KeyManagementException {
		SSLContext sc = SSLContext.getInstance("SSLv3");

		// 实现一个X509TrustManager接口,用于绕过验证,不用修改里面的方法
		X509TrustManager trustManager = new X509TrustManager() {
			@Override
			public void checkClientTrusted(
					java.security.cert.X509Certificate[] paramArrayOfX509Certificate,
					String paramString) throws CertificateException {
			}

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

			@Override
			public java.security.cert.X509Certificate[] getAcceptedIssuers() {
				return null;
			}
		};

		sc.init(null, new TrustManager[] { trustManager }, null);
		return sc;
	}

	/**
	 * ---------------------------------------------------------
	 * 、、、、、、、、、、、使用httpclient、、、、、、、、、、、、 結束
	 * ---------------------------------------------------------
	 */

}

 

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

牟云飞

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值