JAVAhttp请求转https

原先的请求代码

HttpURLConnection connection = (HttpURLConnection) url.openConnection();

修改后的请求代码

// 创建SSL上下文对象并设置信任所有证书的TrustManager
SSLContext sslContext = SSLContext.getInstance("TLS");
TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager() {
	@Override
	public void checkClientTrusted(X509Certificate[] chain, String authType) {}

	@Override
	public void checkServerTrusted(X509Certificate[] chain, String authType) {}

	@Override
	public X509Certificate[] getAcceptedIssuers() { return null; }
}};
sslContext.init(null, trustAllCerts, new SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());
HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();

后面的完全不用变

你可能感兴趣的:(java,https,http)