Как передать небезопасный HttpClient на запрос Volley в Android - PullRequest
1 голос
/ 30 сентября 2019

Я работаю над разработкой приложений для Android, и мое приложение содержит библиотеку Volley для выполнения вызовов API, но я сталкиваюсь с проблемами с SSL: проблема с самозаверяющим сертификатом для URL, который я использовал в коде. но он работает в другом проекте с библиотекой Retrofit, передавая «unsafe HttpClient», поэтому, пожалуйста, дайте мне знать, как я могу решить эту проблему или как я могу передать «unsafe HttpClient» Volley для выполнения вызовов API.

Ответы [ 2 ]

1 голос
/ 30 сентября 2019

Я нашел, и это работает для меня, Пожалуйста, дайте мне знать, что-то не так здесь. Вот код, который нужно добавить, чтобы сделать вызов.

final String url = "YOUR URL";
    RequestQueue queue = Volley.newRequestQueue(this, getHttpStack(url));
    // prepare the Request
    JsonObjectRequest getRequest = new JsonObjectRequest(Request.Method.GET, url, null,
            new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response) {
                    // display response
                    Log.e("test", "Response" + response.toString());
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Log.e("test", "Error.Response: " + error.getMessage());
                }
            }
    );

    queue.add(getRequest);

Вот методы, которые нужно добавить в код.

private HurlStack getHttpStack(String urlToValidate) {
    URL url = null;
    try {
        url = new URL(urlToValidate);
    } catch (MalformedURLException e) {
        e.printStackTrace();
    }
    final String baseUrl = url.getAuthority();
    return new HurlStack() {
        @Override
        protected HttpURLConnection createConnection(final java.net.URL url)
                throws IOException {
            HttpsURLConnection httpsURLConnection = (HttpsURLConnection) super
                    .createConnection(url);
            try {
                httpsURLConnection
                        .setSSLSocketFactory(handleSSLHandshake(httpsURLConnection));
                httpsURLConnection.setHostnameVerifier(new HostnameVerifier() {
                    @Override
                    public boolean verify(String hostname, SSLSession session) {
                        //return true;
                        HostnameVerifier hv =
                                HttpsURLConnection.getDefaultHostnameVerifier();
                        return hv.verify(baseUrl, session);
                    }
                });
            } catch (Exception e) {
                e.printStackTrace();
            }
            return httpsURLConnection;
        }
    };
}

@SuppressLint("TrulyRandom")
public static SSLSocketFactory handleSSLHandshake(HttpsURLConnection connection) {
    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) {
                Log.e("test", "RETURN TRUE: ");
                return true;
            }
        });
        sc.init(null, trustAllCerts, new java.security.SecureRandom());
        SSLSocketFactory newFactory = sc.getSocketFactory();
        connection.setSSLSocketFactory(newFactory);
    } catch (Exception ignored) {
    }

    return connection.getSSLSocketFactory();

}
0 голосов
/ 30 сентября 2019

Попробуйте добавить это к вам AndoidManifest.xml в теге приложения: -

 <uses-library
        android:name="org.apache.http.legacy"
        android:required="false" />
...