使用Android Volley和Trust所有SSL证书发出HTTPS请求

时间:2014-08-25 09:10:51

标签: android ssl android-volley

我想信任我的应用程序中的所有SSL证书。

我在android.app.Application中添加了这些代码。

try {
    TrustManager[] trustAllCerts = new TrustManager[] {
        new X509TrustManager() {
            @Override
            public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
            }

            @Override
            public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
            }

            public X509Certificate[] getAcceptedIssuers() {
                X509Certificate[] myTrustedAnchors = new X509Certificate[0];
                return myTrustedAnchors;
            }
        }
    };

    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 e) {
    Log.e(TAG, "nuke", e);
}

volleyError.networkResponse.statusCode总是500。

我使用firefox转到JSONDataUrl,它运行正常。

帮助!

String JSONDataUrl = "https://something";
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, JSONDataUrl, null,
    new Response.Listener<JSONObject>() {
        @Override
        public void onResponse(JSONObject response) {
            dismissDialog();
            Log.d(TAG, "response: " + response);
            }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError volleyError) {
            dismissDialog();
            if (DEBUG) {
                if (volleyError.networkResponse != null) {
                    Log.e(TAG, "headers: " + volleyError.networkResponse.headers);
                    Log.e(TAG, "statusCode: " + volleyError.networkResponse.statusCode);
                }
            }
            Log.e(TAG, volleyError.toString(), volleyError);
        }
    });
    requestQueue.add(jsonObjectRequest);

0 个答案:

没有答案