Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save jforge/0d388ba10b3db34b2e39 to your computer and use it in GitHub Desktop.

Select an option

Save jforge/0d388ba10b3db34b2e39 to your computer and use it in GitHub Desktop.
public static void checkHttpConnection(String url) throws IOException {
URL _url = new URL(url);
HttpURLConnection connection = ((HttpURLConnection) _url.openConnection());
int status = 0;
try {
status = connection.getResponseCode();
} catch (SSLHandshakeException e) {
connection.disconnect();
disableCertificateValidation();
connection = ((HttpURLConnection) _url.openConnection());
status = connection.getResponseCode();
}
if (status != HttpURLConnection.HTTP_OK) {
if (status == HttpURLConnection.HTTP_MOVED_TEMP || status == HttpURLConnection.HTTP_MOVED_PERM
|| status == HttpURLConnection.HTTP_SEE_OTHER) {
// redirect
String newUrl = connection.getHeaderField("Location");
System.out.println("Redirect " + url + " -> " + newUrl);
checkHttpConnection(newUrl);
} else {
throw new IOException("Response=" + status);
}
}
}
public static void disableCertificateValidation() throws IOException {
// create a trust manager that does not validate certificate chains
TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
@Override
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
}
@Override
public void checkClientTrusted(X509Certificate[] certs, String authType) {}
@Override
public void checkServerTrusted(X509Certificate[] certs, String authType) {}
} };
// ignore differences between given hostname and certificate hostname
HostnameVerifier hv = new HostnameVerifier() {
@Override
public boolean verify(String hostname, SSLSession session) {
return true;
}
};
// install the all-trusting trust manager
try {
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, trustAllCerts, new SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
HttpsURLConnection.setDefaultHostnameVerifier(hv);
System.out.println("Installed all-accepting trust-manager");
} catch (Exception e) {
if (e instanceof IOException) {
throw (IOException) e;
} else {
throw new IOException(e);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment