HttpURLConnection校验问题
在请求的时候遇到报错:
java.security.cert.CertificateException: No subject alternative names present
at sun.security.ssl.Alerts.getSSLException(Alerts.java:192)
at sun.security.ssl.SSLSocketImpl.fatal(SSLSocketImpl.java:1946)
**
对应代码以及报错:
0x01 HttpURLConnection ssl报错解决办法
**
这种报错是校验了服务端证书,如果本地证书库没有信任网站证书,这种证书一般是自己生成的或者不是权威机构颁发的证书
解决办法:在请求之前调用ignoreSsl()方法
/* */
/* */ import java.security.cert.X509Certificate;
/* */ import javax.net.ssl.SSLContext;
/* */
/* */ public class SslUtils/* */ {
/* */ private static void trustAllHttpsCertificates() throws Exception/* */ {
/* 10 */ javax.net.ssl.TrustManager[] trustAllCerts = new javax.net.ssl.TrustManager[1];/* 11 */ javax.net.ssl.TrustManager tm = new miTM();/* 12 */ trustAllCerts[0] = tm;/* 13 */ SSLContext sc = SSLContext.getInstance("SSL");/* 14 */ sc.init(null, trustAllCerts, null);/* 15 */ javax.net.ssl.HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());/* */ }/* *//* */ static class miTM implements javax.net.ssl.TrustManager, javax.net.ssl.X509TrustManager {
/* */ public X509Certificate[] getAcceptedIssuers() {
/* 20 */ return null;/* */ }/* *//* */ public boolean isServerTrusted(X509Certificate[] certs) {
/* 24 */ return true;/* */ }/* *//* */ public boolean isClientTrusted(X509Certificate[] certs) {
/* 28 */ return true;/* */ }/* *//* *//* *//* */ public void checkServerTrusted(X509Certificate[] certs, String authType)/* */ throws java.security.cert.CertificateException/* */ {
}/* *//* *//* */ public void checkClientTrusted(X509Certificate[] certs, String authType)/* */ throws java.security.cert.CertificateException/* */ {
}/* */ }/* *//* *//* */ public static void ignoreSsl()/* */ throws Exception/* */ {
/* 47 */ javax.net.ssl.HostnameVerifier hv = new javax.net.ssl.HostnameVerifier() {
/* */ public boolean verify(String urlHostName, javax.net.ssl.SSLSession session) {
/* 49 */ return true;/* */ }/* 51 */ };/* 52 */ trustAllHttpsCertificates();/* 53 */ javax.net.ssl.HttpsURLConnection.setDefaultHostnameVerifier(hv);/* */ }/* */ }
解决方案:
public static void main(String[] args) throws Exception {
String result="null";
// ignoreSsl();URL url = new URL ("https://xx.xx.xx.xx/");HttpURLConnection connection = (HttpURLConnection) url.openConnection();connection.setRequestMethod("GET");
// connection.connect();//得到响应码int responseCode = connection.getResponseCode();if (responseCode == HttpURLConnection.HTTP_OK) {
StringBuilder sb = new StringBuilder();//得到响应流InputStream is = connection.getInputStream();BufferedReader reader = new BufferedReader(new InputStreamReader (is, "utf-8"));String line = "";while ((line = reader.readLine()) != null) {
sb.append(line).append("\n");}System.out.println (sb);is.close();connection.disconnect();}
}