我正在尝试在 grails 中使用 groovy 的 toURL()
方法发出 http 请求:
def holidayApiUrl = "https://holidayapi.com/v1/holidays?key=${apiKey}&year=2016&country=US"
def holidayJson = JSON.parse(holidayApiUrl.toURL().text)
您可以从 holidayapi.com 获取 api key 来复制此错误。
以上要求给出
PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
所以我一直在寻找在 groovy 中使用此方法完全忽略 ssl 错误的方法。但无法获取。
其他 SO 帖子建议像 this 这样的东西但是 groovy 的 toURL 不使用 SSLContext。那么是否可以使用 toURL() 忽略 ssl 错误?
编辑:
任何想要测试以上代码片段的人都可以免费注册 holidaypi.com 并获得 api key 。在浏览器中点击上面的 url(替换为 api key )会给出正确的 json。但是上面的代码在 groovy 中执行时给出了 SSL 错误。
最佳答案
就在你打电话之前
def holidayJson = new JsonSlurper().parse(holidayApiUrl)
尝试执行以下操作(这会创建并注册替代的 TrustManager):
import javax.net.ssl.SSLContext;
import javax.net.ssl.X509TrustManager;
import javax.net.ssl.HttpsURLConnection;
class TrustManager implements 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) { }
}
TrustManager[] trustAllCerts = new TrustManager[1]
trustAllCerts[0] = new TrustManager()
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, trustAllCerts, new java.security.SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
关于java - 使用 groovy 的 toURL 方法忽略 SSL 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41468036/