2

我们的 android 应用程序指的是HTTP URL从服务器获取一些数据。直到 2 天前它一直正常工作,但突然我们得到"sslpeerunverifiedexception: no peer certificate" exception了,而我们的代码和服务器都没有发生任何变化。代码很简单:

HttpParams httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, 12000);
HttpConnectionParams.setSoTimeout(httpParameters, 12000);
HttpClient client = new DefaultHttpClient(httpParameters);
HttpGet request = new HttpGet("http://site.com");
HttpResponse httpResponse = client.execute(request);
4

2 回答 2

1

在您的代码中添加以下函数。

public HttpClient getNewHttpClient() throws SocketException, UnknownHostException {
    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();
    }
}

并使用下面的代码调用上述函数。

HttpClient httpclient = getNewHttpClient();
于 2013-01-11T10:34:33.807 回答
0

听起来您正在访问的服务器正在使用自签名 SSL 证书。

虽然不推荐(可能是 MiM 攻击),但您可以忽略这一点。有关更多信息,请参阅此帖子:Android 上的自签名 SSL 接受

于 2013-01-11T10:16:56.693 回答