java訪問ssl方法
来源:互联网 发布:r星5淘宝 编辑:程序博客网 时间:2024/06/01 12:46
private static HttpsURLConnection conn;public InsecureConnection(){}public HttpsURLConnection connect(String urlStr, final String userName, final String password) {Authenticator.setDefault (new Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication (userName, password.toCharArray()); }});try{ SSLContext ctx = SSLContext.getInstance("TLS"); ctx.init(new KeyManager[0], new TrustManager[] {new DefaultTrustManager()}, new SecureRandom()); SSLContext.setDefault(ctx); URL url = new URL(urlStr); conn = (HttpsURLConnection) url.openConnection(); conn.setUseCaches(true); conn.setHostnameVerifier(new HostnameVerifier() { @Override public boolean verify(String arg0, SSLSession arg1) { return true; } }); //System.out.println(conn.getResponseCode());}catch(Exception e){e.printStackTrace();}return conn;}public void disconnect(){try{if(conn != null){conn.disconnect();}}catch(Exception e){e.printStackTrace();}}private static class DefaultTrustManager implements X509TrustManager { @Override public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {} @Override public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {} @Override public X509Certificate[] getAcceptedIssuers() { return null; } }
java訪問ssl方法