我需要为我的客户创建应用程序,应用程序的一部分使用 https 连接:
public static void getVersions() throws IOException, ParserConfigurationException, SAXException {
URL u = new URL(VERSION_URL);
HttpsURLConnection c = (HttpsURLConnection) u.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();
InputStream in = c.getInputStream();
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = null;
builder = factory.newDocumentBuilder();
Document d = builder.parse(in);
}
但是当我尝试使用它时,我会得到 IO 异常:“没有受信任的证书 java”。这是我客户的服务,一切都是合法的。我该如何修复这个错误?
最佳答案
您可以将自定义服务器证书放在信任库中,并将其作为资源包含在您的应用程序中。
在创建到该服务器的 HTTPS 连接时,您可以指定此信任库包含受信任的证书。这可以通过创建自己的 SSLSocketFactory 来完成实例
KeyStore trusted = KeyStore.getInstance("BKS");
InputStream in = context.getResources().openRawResource(R.raw.mystore);
trusted.load(in, "mypassword".toCharArray());
in.close();
SSLSocketFactory mySslFact = new SSLSocketFactory(trusted);
关于java - 如何在没有证书的情况下连接到 https 网络服务?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8020183/