我有这个方法使用httpconnection发布。我收到错误sun.security.provider.certpath.SunCertPathBuilderException:当我连接到自签名网站时,无法找到所请求目标的有效证书路径。我如何忽略证书?
def post(url, jsonData){
url = new URL(url)
def connection = url.openConnection()
connection.setRequestMethod("POST")
connection.setRequestProperty("Content-Type", "application/json");
connection.doOutput = true
def writer = new OutputStreamWriter(connection.outputStream)
writer.write(jsonData)
writer.flush()
writer.close()
connection.connect()
def resp = connection.content.text
resp
}
答案 0 :(得分:2)
您需要创建一个禁用ssl验证的函数,并在请求之前调用它。
这是禁用ssl验证所需功能的示例。
void disableSslVerification() throws NoSuchAlgorithmException, KeyManagementException{
// Create a trust manager that does not validate certificate chains
TrustManager[] trustAllCerts = [
new X509TrustManager(){
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null
}
public void checkClientTrusted(X509Certificate[] certs, String authType) {
}
public void checkServerTrusted(X509Certificate[] certs, String authType) {
}
}
]
// Install the all-trusting trust manager
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, trustAllCerts, new java.security.SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
// Create all-trusting host name verifier
HostnameVerifier allHostsValid = new HostnameVerifier() {
public boolean verify(String hostname, SSLSession sslSession) {
return true;
}
};
// Install the all-trusting host verifier
HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
}
然后你需要做
def post(url, jsonData){
disableSslVerification()
url = new URL(url)
...