javax.net.ssl.SSLException:证书中的主机名与Android中不匹配

问题描述:

我正在更新android应用程序的Web服务URL,我们正在使用https协议。我看到我的当前https网址正在工作,但现在我们正在迁移到新域,然后它正在创建问题。javax.net.ssl.SSLException:证书中的主机名与Android中不匹配

我已经检查了很多线程,如javax.net.ssl.SSLException: hostname in certificate didn't match android,但没有找到任何好的答案,主要是回答绕过此安全性或允许所有。

javax.net.ssl.SSLException:主机名的证书不匹配:提前

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

感谢。

+0

您是否在浏览器中尝试了相同的网址,并且您是否遇到任何证书错误? – Panther 2014-10-05 08:59:43

+0

@Panther没有错误,它在浏览器中工作 – 2014-10-05 09:36:21

如果它在浏览器中运行,但在应用程序中不起作用,则可能是缺少SNI支持的问题,请参见Why does android get the wrong ssl certificate? (two domains, one server)

+0

是的,它是在浏览器中,而不是在应用程序中。我们是否也必须在应用程序中为这个ssl连接保留一些证书? – 2014-10-05 09:37:54

+0

不,您必须使用支持SNI的东西,或者您必须为HTTPS服务器分配一个IP地址,以便您不需要使用SNI。有关更多详细信息,请参阅链接问题 – 2014-10-05 10:58:54

看来最好的解决方案是使用HttpsUrlConnection而不是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(); 

然后使用InputStream获取响应正文。

InputStream inputStream = urlConnection.getInputStream();