android: how to accept CA certificate

我的梦境 提交于 2020-01-02 21:02:00

问题


I am trying to make a secure connection to a OCS server through https in android.

I found the EasySSLFactory and EasyX509TrustManager classes to make android trust the certificate but I don't know how to initialize only one time the EasySSLFactory and EasyX509TrustManager objects.

I have the following code to accept a certificate and make a single connection:

    SchemeRegistry schemeRegistry = new SchemeRegistry();

    schemeRegistry.register(new Scheme("https", new EasySSLSocketFactory(),
            443));

    HttpParams params = new BasicHttpParams();
    params.setParameter(ConnManagerPNames.MAX_TOTAL_CONNECTIONS, 3);
    params.setParameter(ConnManagerPNames.MAX_CONNECTIONS_PER_ROUTE,
            new ConnPerRouteBean(1));
    params.setParameter(HttpProtocolParams.USE_EXPECT_CONTINUE, false);
    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setContentCharset(params, "utf8");

    int timeoutConnection = 1000;
    HttpConnectionParams.setConnectionTimeout(params, timeoutConnection);

    int timeoutSocket = 1000;
    HttpConnectionParams.setSoTimeout(params, timeoutSocket);

    clientConnectionManager = new ThreadSafeClientConnManager(params,
            schemeRegistry);

    HttpClient client = new DefaultHttpClient(clientConnectionManager,
            params);

In order to make a new connection in an new method, I have to do write those lines too... Is there a way that I can put them in the class constructor and then do connections in that class without writing that before the connection..

Thank you


回答1:


Look at my blog article. I've posted a detailed description how you can add your desired certificate to a custom keystore and initialize the HttpClient with it.

Hope this helps

EDIT: I havent tried it, but maybe the TrustStrategy interface may help.

You could implement your own TrustStrategy interface and initialize the SSLSocketFactory with the appropriate constructor. Your strategy can just return true (in the isTrusted method), but you should do for security reasons a bit of checking to be sure if the certificate can be considered as trusted (it depends on your needs)

Look at line 35 on my blog article of the SecureHttpClient class. Replace the line with something like this:

SSLSocketFactory sf = new SSLSocketFactory(myTrustStrategy);

Please let me know if this works for you.

Regards



来源:https://stackoverflow.com/questions/4745550/android-how-to-accept-ca-certificate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!