Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javax.net.ssl.SSLException: hostname in certificate didn't match in Android

I am updating the web service URL of the android application, we are using https protocol. I see that my current https URL is working but now we are migrating to new domain then it is creating problem.

I have checked many threads on stackoverflow like javax.net.ssl.SSLException: hostname in certificate didn't match android but didn't find any good answer mostly are answering bypass this security or allow all.

javax.net.ssl.SSLException: hostname in certificate didn't match:

//HttpGet getMethod = new HttpGet(String.format(httpURL));
HttpGet getMethod = new HttpGet(httpURL);
DefaultHttpClient client = new DefaultHttpClient();
ResponseHandler<String> responseHandler = new BasicResponseHandler();
HttpParams params = client.getParams();
params.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 60000);
params.setParameter(CoreConnectionPNames.SO_TIMEOUT, 60000);
client.setParams(params);
responseBody = client.execute(getMethod, responseHandler);
responseBody = responseBody.trim();

Thanks in advance.

like image 450
N Sharma Avatar asked Dec 09 '22 06:12

N Sharma


1 Answers

It seems that the best solution to this is to use HttpsUrlConnection instead of HttpGet.

URL url = new Url(httpURL);
HttpURLConnection urlConnection = (HttpsURLConnection) url.openConnection();
urlConnection.setReadTimeout(60000);
urlConnection.setConnectTimeout(60000);
urlConnection.setRequestMethod("GET");
urlConnection.setDoInput(true);

urlConnection.connect();

Then use InputStream to get the response body.

InputStream inputStream = urlConnection.getInputStream();
like image 94
mattfred Avatar answered Dec 11 '22 10:12

mattfred