最近项目在访问服务器时出现了证书过期问题,需要使用无认证的连接来向服务器请求数据,方法如下:
public static HttpURLConnection prepareConnection(
String serverUrl) throws IOException, MalformedURLException, ProtocolException {
// Create a trust manager that does not validate certificate chains
TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
public void checkClientTrusted(
java.security.cert.X509Certificate[] certs, String authType) {
}
public void checkServerTrusted(
java.security.cert.X509Certificate[] certs, String authType) {
}
} };
// Install the all-trusting trust manager
try {
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, trustAllCerts, new java.security.SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
} catch (GeneralSecurityException e) {
}
// Now you can access an https URL without having the certificate in the
// truststore
URL url = new URL(serverUrl);
HttpURLConnection urlConnection = null;
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setConnectTimeout(Constants.TIMEOUT_4_CONN); // 设置连接主机超时
urlConnection.setReadTimeout(Constants.TIMEOUT_4_READ); // 设置读取数据超时
urlConnection.setDoInput(true);
urlConnection.setDoOutput(true);
urlConnection.connect(); // 打开连接
return urlConnection;
}