public static boolean testCredentials(final String aURL, final String auth) {
try {
URL url = new URL(aURL);
String encodedLoginCreds = new Base64().encodeAsString(auth.getBytes());
if (aURL.toLowerCase().startsWith("https")) {
try {
HttpsURLConnection httpsConnection = (HttpsURLConnection) url.openConnection();
TrustManager[] trustAllCerts = new TrustManager[]{new BusinessIntelligenceX509TrustManager()};
SSLContext sc;
try {
sc = SSLContext.getInstance("SSL");
} catch (NoSuchAlgorithmException noSuchAlgorithmException) {
return false;
}
HostnameVerifier hv = new BusinessIntelligenceHostnameVerifier();
try {
sc.init(null, trustAllCerts, new java.security.SecureRandom());
} catch (KeyManagementException keyManagementException) {
return false;
}
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
HttpsURLConnection.setDefaultHostnameVerifier(hv);
httpsConnection.setDoInput(true);
httpsConnection.setRequestProperty("Authorization", "Basic " + encodedLoginCreds);
httpsConnection.setRequestMethod("GET");
httpsConnection.connect();
int code = httpsConnection.getResponseCode();
System.out.println("https: " + code);
if (code == 200) return true;
} catch (IOException ioe) {
System.out.println("ioe: " + ioe.getMessage());
}
} else if (aURL.toLowerCase().startsWith("http")) {
try {
HttpURLConnection plainConnection = (HttpURLConnection) url.openConnection();
plainConnection.setRequestProperty("Authorization", "Basic " + encodedLoginCreds);
plainConnection.setRequestMethod("GET");
plainConnection.connect();
int code = plainConnection.getResponseCode();
System.out.println("plain: " + code);
if (code == 200) return true;
} catch (IOException ioe) {
System.out.println("ioe: " + ioe.getMessage());
}
}
} catch (MalformedURLException mue) {
System.out.println("mue: " + mue.getMessage());
}
return false;
}
public class BusinessIntelligenceHostnameVerifier implements HostnameVerifier {
@Override
public boolean verify(String arg0, SSLSession arg1) {
return true;
}
}
public class BusinessIntelligenceX509TrustManager implements X509TrustManager {
@Override
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
@Override
public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) {
// no-op
}
@Override
public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) {
// no-op
}
}
Thursday, October 18, 2012
Subscribe to:
Posts (Atom)