下面的代码实现了java使用HttpsURLConnection访问网络ssl,一般用浏览器访问会提示你安装证书或允许访问,其实使用java访问https也是一样的,要么安装证书,要么直接信任,java安装ssl证书比较麻烦,而且一般企业用的证书是没有签名的,所以关于加载ssl证书就以后和和大家一起探讨。下面就是信任https证书的方法,可以直接调用访问https。
package edc2010.biz.base.sms.lanzSms; import java.io.*; import java.net.*; import java.security.KeyManagementException; import java.security.NoSuchAlgorithmException; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import javax.net.ssl.*; public class SendPost{ public static String sendHttps(String url) { String returnString=""; try { SSLContext sc = SSLContext.getInstance("SSL"); sc.init(null, new TrustManager[] { new TrustAnyTrustManager() },new java.security.SecureRandom()); URL console = new URL(url); HttpsURLConnection conn = (HttpsURLConnection) console.openConnection(); conn.setSSLSocketFactory(sc.getSocketFactory()); conn.setHostnameVerifier(new TrustAnyHostnameVerifier()); conn.connect(); InputStream is = conn.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(is)); String sCurrentLine=""; while ((sCurrentLine = reader.readLine()) != null) { returnString += sCurrentLine + "\r\n"; } reader.close(); is.close(); conn.disconnect(); } catch (ConnectException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (KeyManagementException e) { // TODO Auto-generated catch block e.printStackTrace(); } return returnString; } private static class TrustAnyTrustManager implements X509TrustManager { public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { } public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { } public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[] {}; } } private static class TrustAnyHostnameVerifier implements HostnameVerifier { public boolean verify(String hostname, SSLSession session) { return true; } } }