我在通过 Java 与 HTTPS 站点交互时遇到问题。我的程序每次运行时都使用一个带有不受信任证书的 URL。该程序必须在多个系统上运行。目前,我有以下内容:
public class A{
HostnameVerifier hv = new HostnameVerifier(){
public boolean verify(String urlHostName, SSLSession session){
return true;
}
};
HttpsURLConnection.setDefaultHostnameVerifier(hv);
javax.net.ssl.TrustManager[] trustAllCerts = new javax.net.ssl.TrustManager[1];
javax.net.ssl.TrustManager tm = new miTM();
trustAllCerts[0] = tm;
javax.net.ssl.SSLContext sc = null;
try {
sc = javax.net.ssl.SSLContext.getInstance("SSL");
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
try {
sc.init(null, trustAllCerts, null);
} catch (KeyManagementException e) {
e.printStackTrace();
}
javax.net.ssl.HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
}
class miTM implements javax.net.ssl.TrustManager, javax.net.ssl.X509TrustManager{
public java.security.cert.X509Certificate[] getAcceptedIssuers(){
return null;
}
public boolean isServerTrusted(java.security.cert.X509Certificate[] certs){
return true;
}
public boolean isClientTrusted(java.security.cert.X509Certificate[] certs){
return true;
}
public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) throws java.security.cert.CertificateException{
return;
}
public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) throws java.security.cert.CertificateException{
return;
}
}
使用此代码,我可以很好地执行以下操作:
URL url = new URL(urlString);
URLConnection cnx = url.openConnection();
cnx.connect();
InputStream ins = cnx.getInputStream();
BufferedReader in = new BufferedReader(new InputStreamReader(ins));
String curline;
while( (curline = in.readLine()) != null ) {
System.out.println(curline);
}
但是,我不能执行以下操作:
httpClient = new HttpClient();
PostMethod postMethod = null;
int intResult = 0;
postMethod = new PostMethod(authURL);
Enumeration emParams = authParams.propertyNames();
while (emParams.hasMoreElements()) {
String paramName = (String) emParams.nextElement();
String paramValue = authParams.getProperty(paramName);
postMethod.addParameter(paramName, paramValue);
}
intResult = httpClient.executeMethod(postMethod);
postMethod.releaseConnection();
ins.close();
执行 executeMethod(postMethod) 时,我得到 SSLHandshakeException、CertPathBuilderException 等。
我能做些什么来解决这个问题?我正在考虑要么接受证书,要么只是绕过所有证书验证(因为程序在专用网络内部运行)。
谢谢