package com.skyline.electricity.utils;
|
|
import org.springframework.http.client.*;
|
|
import java.io.IOException;
|
import java.net.*;
|
import java.security.*;
|
import java.security.cert.X509Certificate;
|
import javax.net.ssl.*;
|
|
/*public class HttpsClientRequestFactory extends SimpleClientHttpRequestFactory
|
{
|
@Override
|
protected void prepareConnection(final HttpURLConnection connection, final String httpMethod) {
|
try {
|
if (!(connection instanceof HttpsURLConnection)) {
|
throw new RuntimeException("An instance of HttpsURLConnection is expected");
|
}
|
final HttpsURLConnection httpsConnection = (HttpsURLConnection)connection;
|
final TrustManager[] trustAllCerts = { (TrustManager)new HttpsClientRequestFactory.HttpsClientRequestFactory(this) };
|
final SSLContext sslContext = SSLContext.getInstance("TLS");
|
sslContext.init(null, trustAllCerts, new SecureRandom());
|
httpsConnection.setSSLSocketFactory((SSLSocketFactory)new HttpsClientRequestFactory.MyCustomSSLSocketFactory(sslContext.getSocketFactory()));
|
httpsConnection.setHostnameVerifier((HostnameVerifier)new HttpsClientRequestFactory.HttpsClientRequestFactory$2(this));
|
super.prepareConnection((HttpURLConnection)httpsConnection, httpMethod);
|
}
|
catch (Exception e) {
|
e.printStackTrace();
|
}
|
}
|
}*/
|
/**
|
* 兼容调Https接口
|
*/
|
public class HttpsClientRequestFactory extends SimpleClientHttpRequestFactory {
|
|
@Override
|
protected void prepareConnection(HttpURLConnection connection, String httpMethod)
|
throws IOException {
|
if (connection instanceof HttpsURLConnection) {
|
prepareHttpsConnection((HttpsURLConnection) connection);
|
}
|
super.prepareConnection(connection, httpMethod);
|
}
|
|
private void prepareHttpsConnection(HttpsURLConnection connection) {
|
connection.setHostnameVerifier(new SkipHostnameVerifier());
|
try {
|
connection.setSSLSocketFactory(createSslSocketFactory());
|
}
|
catch (Exception ex) {
|
// Ignore
|
}
|
}
|
|
private SSLSocketFactory createSslSocketFactory() throws Exception {
|
SSLContext context = SSLContext.getInstance("TLS");
|
context.init(null, new TrustManager[] { new SkipX509TrustManager() },
|
new SecureRandom());
|
return context.getSocketFactory();
|
}
|
|
private class SkipHostnameVerifier implements HostnameVerifier {
|
|
@Override
|
public boolean verify(String s, SSLSession sslSession) {
|
return true;
|
}
|
|
}
|
|
private static class SkipX509TrustManager implements X509TrustManager {
|
|
@Override
|
public X509Certificate[] getAcceptedIssuers() {
|
return new X509Certificate[0];
|
}
|
|
@Override
|
public void checkClientTrusted(X509Certificate[] chain, String authType) {
|
}
|
|
@Override
|
public void checkServerTrusted(X509Certificate[] chain, String authType) {
|
}
|
|
}
|
}
|