HttpsUrlConnection с клиентским подписанным сертификатом в AndroidStudio - PullRequest
0 голосов
/ 08 октября 2019

спасибо заранее. У меня есть страница подключения, которая имеет метод HTTPurlConnection и менеджер доверия, который позволяет все сертификаты без какой-либо проверки подлинности. Теперь я хочу подключить URL-адрес «HTTPS», а также аутентифицировать сертификат, подписанный клиентом, который я сохранил в папке raw. Хотя в Google есть много примеров, я не знаю, как и с чего начать? пожалуйста, направь меня. Я приложил обе страницы для справки.

Connection.java:

public class Connection {
    private static TrustManager[] trustManagers;
    protected SoapObject result;
    protected String returnvalue;
    HttpURLConnection httpURLConnection;
    HttpTransportSE androidHttpTransport;

    public String checkprogress(SoapObject value, String action, String url) throws TimeoutException {
        try {

            URL urlCon = new URL(url);
            httpURLConnection = (HttpURLConnection) urlCon.openConnection();
            httpURLConnection.connect();


            SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
            //new MarshalBase64().register(envelope);

            envelope.encodingStyle = SoapEnvelope.ENC;
            envelope.bodyOut = value;
            envelope.dotNet = true;
            envelope.setOutputSoapObject(value);
            envelope.setAddAdornments(false);
            envelope.implicitTypes = true;
            allowAllSSL();
            androidHttpTransport = new HttpTransportSE(url);
            androidHttpTransport.call(action, envelope);

            Log.i("Connection", "SOAP Resquest" + androidHttpTransport.requestDump);
            Log.i("Connection", "SOAP Response" + androidHttpTransport.responseDump);
            Log.i("call", "call");

            SoapPrimitive resultsRequestSOAP = (SoapPrimitive) envelope.getResponse();
            Log.i("SoapPrimitive", "Result" + resultsRequestSOAP);
            Log.i("GetAttribute", "Count" + resultsRequestSOAP.getAttributeCount());
            boolean b = Boolean.parseBoolean(resultsRequestSOAP.toString());
            Log.i("", "risultato boolean Straordinario " + b);

            result = (SoapObject) envelope.bodyIn;
            returnvalue = result.getProperty(0).toString();
            System.out.println("reuslt = " + returnvalue);
        } catch (UnknownHostException e) {
            e.printStackTrace();
            System.out.println(" I Have Catched This Exception in Connection" + e);
            returnvalue = "Invalid URL";
        } catch (MalformedURLException e) {
            e.printStackTrace();
            System.out.println("MalFormedException =" + e);
            returnvalue = "Invalid URL";
        } catch (UnsupportedOperationException uoe) {
            uoe.printStackTrace();
            System.out.println("IllegalArgumentsException =" + uoe);
            returnvalue = "Invalid URL";
        } catch (SocketTimeoutException e) {
            e.printStackTrace();
            System.out.println("SocketTimeoutException =" + e);
            returnvalue = "Timeout";
        } catch (IOException e) {
            e.printStackTrace();
            returnvalue = "Couldn't connect to server";
        } catch (XmlPullParserException e) {
            e.printStackTrace();
            returnvalue = "Invalid URL";
        } catch (NullPointerException ne) {
            ne.printStackTrace();
            returnvalue = "Invalid URL";
        }finally {
            try {
                androidHttpTransport.getServiceConnection().disconnect();
                httpURLConnection.disconnect();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

        return returnvalue;
    }

    public static void allowAllSSL() {

        javax.net.ssl.HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        });

        javax.net.ssl.SSLContext context = null;

        if (trustManagers == null) {
            trustManagers = new javax.net.ssl.TrustManager[] { new _FakeX509TrustManager() };
        }

        try {
            context = javax.net.ssl.SSLContext.getInstance("TLS");
            context.init(null, trustManagers, new SecureRandom());
        } catch (NoSuchAlgorithmException e) {
            Log.e("allowAllSSL", e.toString());
        } catch (KeyManagementException e) {
            Log.e("allowAllSSL", e.toString());
        }
        javax.net.ssl.HttpsURLConnection.setDefaultSSLSocketFactory(context.getSocketFactory());
    }
}

_FakeX509TrustManager .java:

public class _FakeX509TrustManager implements javax.net.ssl.X509TrustManager {
    private static final X509Certificate[] _AcceptedIssuers = new X509Certificate[] {};

    public void checkClientTrusted(X509Certificate[] arg0, String arg1)
            throws CertificateException {
    }
    public void checkServerTrusted(X509Certificate[] arg0, String arg1)
            throws CertificateException {
    }

    public boolean isClientTrusted(X509Certificate[] chain) {
        return (true);
    }
    public boolean isServerTrusted(X509Certificate[] chain) {
        return (true);
    }

    public X509Certificate[] getAcceptedIssuers() {
        return (_AcceptedIssuers);
    }
}

...