DefaultHttpClient在HTTP请求上获取ssl异常

时间:2013-01-11 09:27:57

标签: android ssl httprequest

我们的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);

2 个答案:

答案 0 :(得分: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();

答案 1 :(得分:0)

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

虽然不推荐(可能是MiM攻击),但你可以忽略它。有关详情,请参阅此帖子:Self-signed SSL acceptance on Android