0

我正在尝试将我的 android 应用程序连接到属于私人公司的 url,以便检索和发送信息。但是,当我这样做时,我收到一个错误 Trust anchor for certificate path not found,但 url 的 ssl 证书是有效的,我做了研究,我使用了以下代码,我曾经在类 Http TrustManager 中信任证书

         public class HttpsTrustManager {
public void trust() throws CertificateException, IOException, KeyStoreException, NoSuchAlgorithmException {

    CertificateFactory cf = CertificateFactory.getInstance("X.509");

    InputStream caInput = new BufferedInputStream(new FileInputStream("load-der.crt"));
    Certificate ca;
    try {
        ca = cf.generateCertificate(caInput);
        out.println("ca=" + ((X509Certificate) ca).getSubjectDN());
    } finally {
        caInput.close();
    }

    String keyStoreType = KeyStore.getDefaultType();
    KeyStore keyStore = KeyStore.getInstance(keyStoreType);
    keyStore.load(null, null);
    keyStore.setCertificateEntry("ca", ca);

    String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
    TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
    tmf.init(keyStore);


    SSLContext context = null;
    try {
        context = SSLContext.getInstance("TLS");
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    }
    try {
        context.init(null, tmf.getTrustManagers(), null);
    } catch (KeyManagementException e) {
        e.printStackTrace();
    }

    // Tell the URLConnection to use a SocketFactory from our SSLContext
    URL url = new URL("https://systems.syspearl.com/api");
    HttpsURLConnection urlConnection =
            (HttpsURLConnection) url.openConnection();
    urlConnection.setSSLSocketFactory(context.getSocketFactory());
    InputStream in = urlConnection.getInputStream();
    IOUtils.copyStream(in,out);

}

这就是我在主要活动中的称呼

       new HttpsTrusrtManger().trust();

然而,这不起作用。请提供必要的帮助

4

0 回答 0