抛出的错误是这样的:
javax.net.ssl.SSLException: hostname in certificate didn't match: <test.rigbee.cn> != <rigbee.cn> OR <rigbee.cn> OR <www.rigbee.cn>
at org.apache.http.conn.ssl.AbstractVerifier.verify(AbstractVerifier.java:185)
at org.apache.http.conn.ssl.BrowserCompatHostnameVerifier.verify(BrowserCompatHostnameVerifier.java:54)
at org.apache.http.conn.ssl.AbstractVerifier.verify(AbstractVerifier.java:114)
at org.apache.http.conn.ssl.AbstractVerifier.verify(AbstractVerifier.java:95)
at org.apache.http.conn.ssl.SSLSocketFactory.createSocket(SSLSocketFactory.java:381)
at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:165)
at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
尝试过设置HttpsURLConnection.setDefaultHostnameVerifier(),不成功,估计是org.apache.http有自己的一套SSL东西,修改org.apache.http的主机名验证解决问题。
增加则用的一行:
SSLSocketFactory.getSocketFactory().setHostnameVerifier(new AllowAllHostnameVerifier());
同时import一下:
import org.apache.http.conn.ssl.AllowAllHostnameVerifier;
import org.apache.http.conn.ssl.SSLSocketFactory;
如果你使用org.apache.http的话上面的就够了。
另外如果你使用原始的URLConnect的话请这样设置一下:
try {
SSLContext sc = SSLContext.getInstance("TLS");
sc.init(null, new TrustManager[] { new X509TrustManager() {
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
}
@Override
public X509Certificate[] getAcceptedIssuers() {
return null;
}
} }, new SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
@Override
public boolean verify(String arg0, SSLSession arg1) {
return true;
}
});
} catch (Exception e) {
e.printStackTrace();
}
之后就可以使用了:
String https = "https://www.google.com.hk";
try {
HttpsURLConnection conn = (HttpsURLConnection) new URL(https).openConnection();
conn.setDoOutput(true);
conn.setDoInput(true);
conn.connect();
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuffer sb = new StringBuffer();
String line;
while ((line = br.readLine()) != null)
sb.append(line);
Log(sb.toString());
} catch (Exception e) {
e.printStackTrace();
}