kazemipouya
kazemipouya

Reputation: 95

DefaultHttpClient get ssl exception on HTTP request

Our android app is referring to HTTP URL to get some data from server. It was working properly till 2 days ago but suddenly we get "sslpeerunverifiedexception: no peer certificate" exception while no changes happen neither in our code nor in server. The code is quite simple:

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);

Upvotes: 2

Views: 1996

Answers (2)

Dipak Keshariya
Dipak Keshariya

Reputation: 22291

Add below function in your code.

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();
    }
}

And Use below code for call above function.

HttpClient httpclient = getNewHttpClient();

Upvotes: 1

Chris Banes
Chris Banes

Reputation: 31871

It sounds like the server you're accessing is using a self-signed SSL certificate.

While not recommended (could be a MiM attack) you can just ignore this. See this post for more info: Self-signed SSL acceptance on Android

Upvotes: 0

Related Questions