Android凌空错误:"找不到证书路径的信任锚",仅在真实设备中,而不是模拟器

Sam*_*tte 7 android android-volley

我在我的Android应用程序中遇到问题,在我的一个片段中,我使用volley来执行网络请求:

JsonObjectRequest request = new JsonObjectRequest(
            Request.Method.POST,
            CustomNetworkManager.getInstance(this.getActivity().getApplicationContext()).getRequestUrl(url),
            requestData,
            new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response) {
                    // process response
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Log.d("FeedFragment", "Volley error: " + error.toString());
                }
            });
Run Code Online (Sandbox Code Playgroud)

在真实设备上,我收到以下错误(运行API23):

D/FeedFragment: Volley error: com.android.volley.NoConnectionError: javax.net.ssl.SSLHandshakeException: java.security.cert.CertPathValidatorException: Trust anchor for certification path not found.
Run Code Online (Sandbox Code Playgroud)

在运行相同API版本的AVD中,它工作正常.我检查了其他类似的线程,但找不到答案.

谢谢你的帮助.

编辑:如果有人遇到相同的错误,请确保您的证书没有任何问题(http://developer.android.com/intl/pt-br/training/articles/security-ssl.html#CommonProblems)

OSh*_*fer 20

尝试将此功能添加到您的应用程序:

    /**
     * Enables https connections
     */
    @SuppressLint("TrulyRandom")
    public static void handleSSLHandshake() {
        try {
            TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager() {
                public X509Certificate[] getAcceptedIssuers() {
                    return new X509Certificate[0];
                }

                @Override
                public void checkClientTrusted(X509Certificate[] certs, String authType) {
                }

                @Override
                public void checkServerTrusted(X509Certificate[] certs, String authType) {
                }
            }};

            SSLContext sc = SSLContext.getInstance("SSL");
            sc.init(null, trustAllCerts, new SecureRandom());
            HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
            HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
                @Override
                public boolean verify(String arg0, SSLSession arg1) {
                    return true;
                }
            });
        } catch (Exception ignored) {
        }
    }
Run Code Online (Sandbox Code Playgroud)

然后在您的Application onCreate中调用它.

更新:

此代码不相关,不应使用!它是被谷歌禁止的.有关更多信息,看这里.