Https Connection Android

后端 未结 15 1671
萌比男神i
萌比男神i 2020-11-22 04:43

I am doing a https post and I\'m getting an exception of ssl exception Not trusted server certificate. If i do normal http it is working perfectly fine. Do I have to accept

相关标签:
15条回答
  • 2020-11-22 05:23

    Any of this answers didn't work for me so here is code which trust any certificates.

    import java.io.IOException;
    
        import java.net.Socket;
        import java.security.KeyManagementException;
        import java.security.KeyStoreException;
        import java.security.NoSuchAlgorithmException;
        import java.security.UnrecoverableKeyException;
        import java.security.cert.CertificateException;
        import java.security.cert.X509Certificate;
    
        import javax.net.ssl.SSLContext;
        import javax.net.ssl.TrustManager;
        import javax.net.ssl.X509TrustManager;
    
        import org.apache.http.client.ClientProtocolException;
        import org.apache.http.client.HttpClient;
        import org.apache.http.client.methods.HttpPost;
        import org.apache.http.conn.scheme.PlainSocketFactory;
        import org.apache.http.conn.scheme.Scheme;
        import org.apache.http.conn.scheme.SchemeRegistry;
        import org.apache.http.conn.ssl.SSLSocketFactory;
        import org.apache.http.conn.ssl.X509HostnameVerifier;
        import org.apache.http.impl.client.DefaultHttpClient;
        import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
        import org.apache.http.params.BasicHttpParams;
    import org.apache.http.params.HttpConnectionParams;
    import org.apache.http.params.HttpParams;
    
        public class HttpsClientBuilder {
            public static DefaultHttpClient getBelieverHttpsClient() {
    
                DefaultHttpClient client = null;
    
                SchemeRegistry Current_Scheme = new SchemeRegistry();
                Current_Scheme.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
                try {
                    Current_Scheme.register(new Scheme("https", new Naive_SSLSocketFactory(), 8443));
                } catch (KeyManagementException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (UnrecoverableKeyException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (NoSuchAlgorithmException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (KeyStoreException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                HttpParams Current_Params = new BasicHttpParams();
                int timeoutConnection = 8000;
                HttpConnectionParams.setConnectionTimeout(Current_Params, timeoutConnection);
                int timeoutSocket = 10000;
                HttpConnectionParams.setSoTimeout(Current_Params, timeoutSocket);
                ThreadSafeClientConnManager Current_Manager = new ThreadSafeClientConnManager(Current_Params, Current_Scheme);
                client = new DefaultHttpClient(Current_Manager, Current_Params);
                //HttpPost httpPost = new HttpPost(url);
                //client.execute(httpPost);
    
             return client;
             }
    
        public static class Naive_SSLSocketFactory extends SSLSocketFactory
        {
            protected SSLContext Cur_SSL_Context = SSLContext.getInstance("TLS");
    
            public Naive_SSLSocketFactory ()
                    throws NoSuchAlgorithmException, KeyManagementException,
                    KeyStoreException, UnrecoverableKeyException
            {
                super(null, null, null, null, null, (X509HostnameVerifier)null);
                Cur_SSL_Context.init(null, new TrustManager[] { new X509_Trust_Manager() }, null);
            }
    
            @Override
            public Socket createSocket(Socket socket, String host, int port,
                    boolean autoClose) throws IOException
            {
                return Cur_SSL_Context.getSocketFactory().createSocket(socket, host, port, autoClose);
            }
    
            @Override
            public Socket createSocket() throws IOException
            {
                return Cur_SSL_Context.getSocketFactory().createSocket();
            }
        }
    
        private static class X509_Trust_Manager implements X509TrustManager
        {
    
            public void checkClientTrusted(X509Certificate[] chain, String authType)
                    throws CertificateException {
                // TODO Auto-generated method stub
    
            }
    
            public void checkServerTrusted(X509Certificate[] chain, String authType)
                    throws CertificateException {
                // TODO Auto-generated method stub
    
            }
    
            public X509Certificate[] getAcceptedIssuers() {
                // TODO Auto-generated method stub
                return null;
            }
    
        };
    }
    
    0 讨论(0)
  • 2020-11-22 05:25

    I'm making a guess, but if you want an actual handshake to occur, you have to let android know of your certificate. If you want to just accept no matter what, then use this pseudo-code to get what you need with the Apache HTTP Client:

    SchemeRegistry schemeRegistry = new SchemeRegistry ();
    
    schemeRegistry.register (new Scheme ("http",
        PlainSocketFactory.getSocketFactory (), 80));
    schemeRegistry.register (new Scheme ("https",
        new CustomSSLSocketFactory (), 443));
    
    ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager (
        params, schemeRegistry);
    
    
    return new DefaultHttpClient (cm, params);
    

    CustomSSLSocketFactory:

    public class CustomSSLSocketFactory extends org.apache.http.conn.ssl.SSLSocketFactory
    {
    private SSLSocketFactory FACTORY = HttpsURLConnection.getDefaultSSLSocketFactory ();
    
    public CustomSSLSocketFactory ()
        {
        super(null);
        try
            {
            SSLContext context = SSLContext.getInstance ("TLS");
            TrustManager[] tm = new TrustManager[] { new FullX509TrustManager () };
            context.init (null, tm, new SecureRandom ());
    
            FACTORY = context.getSocketFactory ();
            }
        catch (Exception e)
            {
            e.printStackTrace();
            }
        }
    
    public Socket createSocket() throws IOException
    {
        return FACTORY.createSocket();
    }
    
     // TODO: add other methods like createSocket() and getDefaultCipherSuites().
     // Hint: they all just make a call to member FACTORY 
    }
    

    FullX509TrustManager is a class that implements javax.net.ssl.X509TrustManager, yet none of the methods actually perform any work, get a sample here.

    Good Luck!

    0 讨论(0)
  • 2020-11-22 05:25

    I don't know about the Android specifics for ssl certificates, but it would make sense that Android won't accept a self signed ssl certificate off the bat. I found this post from android forums which seems to be addressing the same issue: http://androidforums.com/android-applications/950-imap-self-signed-ssl-certificates.html

    0 讨论(0)
  • 2020-11-22 05:25

    I make this class and found

    package com.example.fakessl;
    
    import java.security.KeyManagementException;
    import java.security.NoSuchAlgorithmException;
    import java.security.SecureRandom;
    import java.security.cert.CertificateException;
    import java.security.cert.X509Certificate;
    
    import javax.net.ssl.HostnameVerifier;
    import javax.net.ssl.SSLSession;
    import javax.net.ssl.TrustManager;
    
    import android.util.Log;
    
    public class CertificadoAceptar {
        private static TrustManager[] trustManagers;
    
        public static 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);
            }
        }
    
        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());
        }
    }
    

    in you code white this

    CertificadoAceptar ca = new CertificadoAceptar();
    ca.allowAllSSL();
    HttpsTransportSE Transport = new HttpsTransportSE("iphost or host name", 8080, "/WS/wsexample.asmx?WSDL", 30000);
    
    0 讨论(0)
  • 2020-11-22 05:29

    Probably you can try something like this. This helped me

        SslContextFactory sec = new SslContextFactory();
        sec.setValidateCerts(false);
        sec.setTrustAll(true);
    
        org.eclipse.jetty.websocket.client.WebSocketClient client = new WebSocketClient(sec);
    
    0 讨论(0)
  • 2020-11-22 05:33

    Just use this method as your HTTPClient:

    public static  HttpClient getNewHttpClient() {
        try {
            KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
            trustStore.load(null, null);
    
            SSLSocketFactory sf = new MySSLSocketFactory(trustStore);
            sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    
            HttpParams params = new BasicHttpParams();
            HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
            HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
    
            SchemeRegistry registry = new SchemeRegistry();
            registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
            registry.register(new Scheme("https", sf, 443));
    
            ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);
    
            return new DefaultHttpClient(ccm, params);
        } catch (Exception e) {
            return new DefaultHttpClient();
        }
    }
    
    0 讨论(0)
提交回复
热议问题