public class HttpsTrustManager {
public static SSLContext getSSLContext(InputStream... certificates) {
try {
CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
keyStore.load(null);
int index = 0;
for (InputStream certificate : certificates) {
String certificateAlias = Integer.toString(index++);
keyStore.setCertificateEntry(certificateAlias, certificateFactory.generateCertificate(certificate));
try {
if (certificate != null)
certificate.close();
} catch (IOException e) {
}
}
SSLContext sslContext = SSLContext.getInstance("TLS");
TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
trustManagerFactory.init(keyStore);
sslContext.init(null, trustManagerFactory.getTrustManagers(), new SecureRandom());
return sslContext;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static String CER_baidu="-----BEGIN CERTIFICATE-----\n" +
"MIIFVzCCBD+gAwIBAgIQQKY1foNn0BsYOq8TIk8hojANBgkqhkiG9w0BAQUFADCBtTELMAkGA1UE\n" +
"BhMCVVMxFzAVBgNVBAoTDlZlcmlTaWduLCBJbmMuMR8wHQYDVQQLExZWZXJpU2lnbiBUcnVzdCBO\n" +
"ZXR3b3JrMTswOQYDVQQLEzJUZXJtcyBvZiB1c2UgYXQgaHR0cHM6Ly93d3cudmVyaXNpZ24uY29t\n" +
"L3JwYSAoYykxMDEvMC0GA1UEAxMmVmVyaVNpZ24gQ2xhc3MgMyBTZWN1cmUgU2VydmVyIENBIC0g\n" +
"RzMwHhcNMTUwNTI3MDAwMDAwWhcNMTUxMjI4MjM1OTU5WjCBqTELMAkGA1UEBhMCQ04xEDAOBgNV\n" +
"BAgTB2JlaWppbmcxEDAOBgNVBAcUB2JlaWppbmcxOTA3BgNVBAoUMEJlaUppbmcgQmFpZHUgTmV0\n" +
"Y29tIFNjaWVuY2UgVGVjaG5vbG9neSBDby4sIEx0ZDElMCMGA1UECxQcc2VydmljZSBvcGVyYXRp\n" +
"b24gZGVwYXJ0bWVudDEUMBIGA1UEAxQLK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PQ4PSeHyHCSbQ2m5vX2E+0DhUf0rwMhn4oOHQFuzqHKlWPxA51U\n" +
"5pSJnjTpkS1Hpj7GAz0z0+b2dV7a3//rawJojk2kEog9aVw5U+9fBnXWeO3lhCtNSMrjAy/+7hGd\n" +
"/9g59JBSSskd2yoCM0I1wJ7HK1AYoWtZRO1Ufe2I1PfbeY7k520C0x9hIEXDDVdjurHOiUU2rNz7\n" +
"AjENeXtjpcn8ejx0V92X8ZnA00bZSrVrOYe+0L56yJxhFUm2aNeOPAaTGk7M7CwWQv0t0FhzcfT0\n" +
"8UwL\n" +
"-----END CERTIFICATE-----";
* 将一个字符串转化为输入流
*/
public static InputStream getStringStream(String sInputString){
if (sInputString != null && !sInputString.trim().equals("")){
try{
ByteArrayInputStream tInputStringStream = new ByteArrayInputStream(sInputString.getBytes("UTF-8"));
return tInputStringStream;
}catch (Exception ex){
ex.printStackTrace();
}
}
return null;
}
}
SSLContext sslContext= HttpsTrustManager.getSSLContext(HttpsTrustManager.getStringStream(HttpsTrustManager.CER_baidu));
HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());