如何在Square MockWebServer中使用SSL?

时间:2015-12-02 07:56:42

标签: android ssl https square mockwebserver

我尝试在Square's MockWebServer 上启用SSL来模拟我的Android应用中的所有网络服务调用。我想启用SSL以获得与真实条件相同的错误。我不想为测试禁用SSL或实现SSL忽略的HTTPClient。

每次请求我都会收到 javax.net.ssl.SSLPeerUnverifiedExceptionecxeption

org.springframework.web.client.ResourceAccessException: I/O error on POST request for "https://localhost:42451/api/blabla": No peer certificate; nested exception is javax.net.ssl.SSLPeerUnverifiedException: No peer certificate

似乎我需要为MockWebServer设置证书。但我不知道怎么......

这是我尝试启用SSL的方式:

SSLContext sslContext = new SslContextBuilder(InetAddress.getLocalHost().getHostName()).build();
server.useHttps(sslContext.getSocketFactory(), true);

或者:

SSLContext sslContext = SSLContext.getInstance("SSL");
sslContext.init(null, null, null);
server.useHttps(sslContext.getSocketFactory(), false);

有人可以帮忙吗?

2 个答案:

答案 0 :(得分:1)

您需要创建自己的密钥库:

keytool -genkey -v -keystore mystore.keystore.jks -alias alias_name -keyalg RSA -keysize 2048 -validity 10000

或参见:https://developer.android.com/studio/publish/app-signing.html

创建密钥库后,将其加载到代码中并按以下方式使用它:

        FileInputStream stream = new FileInputStream("mystore.keystore.jks");
        char[] serverKeyStorePassword = "yourcode".toCharArray();
        KeyStore serverKeyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        serverKeyStore.load(stream, serverKeyStorePassword);

        String kmfAlgorithm = KeyManagerFactory.getDefaultAlgorithm();
        KeyManagerFactory kmf = KeyManagerFactory.getInstance(kmfAlgorithm);
        kmf.init(serverKeyStore, serverKeyStorePassword);

        TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(kmfAlgorithm);
        trustManagerFactory.init(serverKeyStore);

        SSLContext sslContext = SSLContext.getInstance("SSL");
        sslContext.init(kmf.getKeyManagers(), trustManagerFactory.getTrustManagers(), null);
        SSLSocketFactory sf = sslContext.getSocketFactory();
        mockWebServer.useHttps(sf, false);

答案 1 :(得分:-1)

我就是这样做的:

 MockWebServer serverForHttps = new MockWebServer();
 serverForHttps .useHttps(SslContextBuilder.localhost().getSocketFactory(), false);
 serverForHttps .start()

它对我有用。