Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java SSLException: hostname in certificate didn't match

Tags:

java

https

ssl

I have been using the following code to connect to one of google's service. This code worked fine on my local machine :

HttpClient client=new DefaultHttpClient(); HttpPost post = new HttpPost("https://www.google.com/accounts/ClientLogin"); post.setEntity(new UrlEncodedFormEntity(myData)); HttpResponse response = client.execute(post); 

I put this code in a production environment, which had blocked Google.com. On request, they allowed communication with Google server by allowing me to accessing an IP : 74.125.236.52 - which is one of Google's IPs. I edited my hosts file to add this entry too.

Still I could not access the URL, which I wonder why. So I replaced the above code with :

HttpPost post = new HttpPost("https://74.125.236.52/accounts/ClientLogin"); 

Now I get an error like this :

javax.net.ssl.SSLException: hostname in certificate didn't match: <74.125.236.52> != <www.google.com>

I guess this is because Google has multiple IPs. I cant ask the network admin to allow me access to all those IPs - I may not even get this entire list.

What should I do now ? Is there a workaround at Java level ? Or is it totally in hands of the network guy ?

like image 678
WinOrWin Avatar asked Aug 31 '11 12:08

WinOrWin


1 Answers

You can also try to set a HostnameVerifier as described here. This worked for me to avoid this error.

// Do not do this in production!!! HostnameVerifier hostnameVerifier = org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;  DefaultHttpClient client = new DefaultHttpClient();  SchemeRegistry registry = new SchemeRegistry(); SSLSocketFactory socketFactory = SSLSocketFactory.getSocketFactory(); socketFactory.setHostnameVerifier((X509HostnameVerifier) hostnameVerifier); registry.register(new Scheme("https", socketFactory, 443)); SingleClientConnManager mgr = new SingleClientConnManager(client.getParams(), registry); DefaultHttpClient httpClient = new DefaultHttpClient(mgr, client.getParams());  // Set verifier      HttpsURLConnection.setDefaultHostnameVerifier(hostnameVerifier);  // Example send http request final String url = "https://encrypted.google.com/";   HttpPost httpPost = new HttpPost(url); HttpResponse response = httpClient.execute(httpPost); 
like image 91
H6. Avatar answered Sep 22 '22 19:09

H6.