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方法java訪問ssl方法
最新推荐文章于 2024-08-20 09:01:18 发布