Thursday, July 17, 2014

Trust all hosts when send https request – How to avoid SSL error when we connect https service

Sometimes when we write client applications we might need to communicate with services exposed over SSL. Some scenarios we might need to skip certificate check from client side. This is bit risky but if we know server and we can trust it we can skip certificate check. Also we can skip host name verification. So basically we are going to trust all certs. See following sample code.

//Connect to Https service     
HttpsURLConnection  conHttps = (HttpsURLConnection) new URL(urlVal).openConnection();
                //We will skip host name verification as this is just testing endpoint. This verification skip
                //will be limited only for this connection
                //call trust all hosts method then we will trust all certs
                if (conHttps.getResponseCode() == HttpURLConnection.HTTP_OK) {
                    return "success";

//Required utility methods
static HostnameVerifier DO_NOT_VERIFY = new HostnameVerifier() {
    public boolean verify(String hostname, SSLSession session) {
        return true;

private static void trustAllHosts() {
    // Create a trust manager that does not validate certificate chains
    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
        public[] getAcceptedIssuers() {
            return new[] {};

        public void checkClientTrusted(X509Certificate[] chain,
                                       String authType) throws CertificateException {

        public void checkServerTrusted(X509Certificate[] chain,
                                       String authType) throws CertificateException {
    } };

    // Install the all-trusting trust manager
    try {
        SSLContext sc = SSLContext.getInstance("TLS");
        sc.init(null, trustAllCerts, new;
    } catch (Exception e) {

No comments:

Post a Comment