Example usage for org.apache.http.conn.ssl SSLSocketFactory ALLOW_ALL_HOSTNAME_VERIFIER

List of usage examples for org.apache.http.conn.ssl SSLSocketFactory ALLOW_ALL_HOSTNAME_VERIFIER

Introduction

In this page you can find the example usage for org.apache.http.conn.ssl SSLSocketFactory ALLOW_ALL_HOSTNAME_VERIFIER.

Prototype

X509HostnameVerifier ALLOW_ALL_HOSTNAME_VERIFIER

To view the source code for org.apache.http.conn.ssl SSLSocketFactory ALLOW_ALL_HOSTNAME_VERIFIER.

Click Source Link

Usage

From source file:org.xdi.oxauth.BaseTest.java

public static DefaultHttpClient createHttpClient(HostnameVerifierType p_verifierType) {
    if (p_verifierType != null && p_verifierType != HostnameVerifierType.DEFAULT) {
        switch (p_verifierType) {
        case ALLOW_ALL:
            HostnameVerifier hostnameVerifier = org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;

            DefaultHttpClient client = new DefaultHttpClient();

            SchemeRegistry registry = new SchemeRegistry();
            SSLSocketFactory socketFactory = SSLSocketFactory.getSocketFactory();
            socketFactory.setHostnameVerifier((X509HostnameVerifier) hostnameVerifier);
            registry.register(new Scheme("https", socketFactory, 443));
            SingleClientConnManager mgr = new SingleClientConnManager(client.getParams(), registry);

            // Set verifier
            HttpsURLConnection.setDefaultHostnameVerifier(hostnameVerifier);
            return new DefaultHttpClient(mgr, client.getParams());
        case DEFAULT:
            return new DefaultHttpClient();
        }//from  www .  j  ava2 s  . c o  m
    }
    return new DefaultHttpClient();
}

From source file:com.haoqee.chatsdk.net.Utility.java

public static HttpClient getNewHttpClient(long timeout) {
    try {/*from  w w w .  jav a  2s.c o  m*/
        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(null, null);

        SSLSocketFactory sf = new MySSLSocketFactory(trustStore);
        sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

        HttpParams params = new BasicHttpParams();

        //HttpConnectionParams.setConnectionTimeout(params, 10000);
        //HttpConnectionParams.setSoTimeout(params, 10000);

        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
        //HttpProtocolParams.setContentCharset(params, HTTP.);

        SchemeRegistry registry = new SchemeRegistry();
        registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
        registry.register(new Scheme("https", sf, 443));

        ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);

        // Set the default socket timeout (SO_TIMEOUT) // in
        // milliseconds which is the timeout for waiting for data.
        HttpConnectionParams.setConnectionTimeout(params, Utility.SET_CONNECTION_TIMEOUT);
        long soc_time = Utility.SET_SOCKET_TIMEOUT + timeout;
        HttpConnectionParams.setSoTimeout(params, (int) soc_time);
        HttpClient client = new DefaultHttpClient(ccm, params);
        return client;
    } catch (Exception e) {
        return new DefaultHttpClient();
    }
}

From source file:org.fedoraproject.eclipse.packager.api.UploadSourceCommand.java

/**
 * Wrap a basic HttpClient object in a Fedora SSL enabled HttpClient (which includes
 * Fedora SSL authentication cert) object.
 * /*  w  w  w.  ja  v a  2 s  .  c o  m*/
 * @param base The HttpClient to wrap.
 * @return The SSL wrapped HttpClient.
 * @throws GeneralSecurityException
 * @throws IOException
 */
private HttpClient fedoraSslEnable(HttpClient base)
        throws GeneralSecurityException, FileNotFoundException, IOException {

    // Get a SSL related instance for setting up SSL connections.
    FedoraSSL fedoraSSL = FedoraSSLFactory.getInstance();
    SSLSocketFactory sf = new SSLSocketFactory(fedoraSSL.getInitializedSSLContext(), // may throw FileNotFoundE
            SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    ClientConnectionManager ccm = base.getConnectionManager();
    SchemeRegistry sr = ccm.getSchemeRegistry();
    Scheme https = new Scheme("https", 443, sf); //$NON-NLS-1$
    sr.register(https);
    return new DefaultHttpClient(ccm, base.getParams());
}

From source file:immf.AppNotifications.java

private void send(String message, String command) throws Exception {
    String url = PushUrl;//www .  ja va2  s  .c o m
    DefaultHttpClient httpClient = new DefaultHttpClient();

    // appnotifications?DNS???IP??
    // ??SSL???????????
    if (dnsCache) {
        InetAddress ipaddr;
        try {
            ipaddr = InetAddress.getByName(PushHost);
            this.pushaddr = ipaddr;
        } catch (UnknownHostException e) {
            if (pushaddr != null) {
                log.warn("DNS lookup error, using cache...");
                ipaddr = this.pushaddr;
            } else {
                throw (e);
            }
        }

        SSLSocketFactory sf = SSLSocketFactory.getSocketFactory();
        sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        Scheme sc = new Scheme("https", sf, 443);
        httpClient.getConnectionManager().getSchemeRegistry().register(sc);
        url = "https://" + ipaddr.getHostAddress() + PushPath;
    }

    HttpPost post = new HttpPost(url);
    post.setHeader("Host", PushHost); // dnsCache
    List<NameValuePair> formparams = new ArrayList<NameValuePair>();
    formparams.add(new BasicNameValuePair("user_credentials", this.credentials));
    if (!this.sound.isEmpty()) {
        formparams.add(new BasicNameValuePair("notification[sound]", this.sound));
    }
    formparams.add(new BasicNameValuePair("notification[message]", message));
    formparams.add(new BasicNameValuePair("notification[icon_url]", this.iconUrl));
    formparams.add(new BasicNameValuePair("notification[message_level]", "2"));
    formparams.add(new BasicNameValuePair("notification[silent]", "0"));
    if (command != null && !command.isEmpty()) {
        // ??????action_loc_key???
        formparams.add(new BasicNameValuePair("notification[action_loc_key]", "Reply"));
        formparams.add(new BasicNameValuePair("notification[run_command]", command));
    } else {
        formparams.add(new BasicNameValuePair("notification[action_loc_key]", ""));
    }
    UrlEncodedFormEntity entity = null;
    try {
        entity = new UrlEncodedFormEntity(formparams, "UTF-8");
    } catch (Exception e) {
    }
    post.setEntity(entity);
    try {
        HttpResponse res = httpClient.execute(post);
        int status = res.getStatusLine().getStatusCode();
        if (status != 200) {
            if (status >= 500) {
                throw new MyHttpException("http server error. status=" + status);
            } else {
                throw new Exception("http server error. status=" + status);
            }
        }
        String resString = EntityUtils.toString(res.getEntity());
        log.info("?:" + resString);
        JSONObject json = JSONObject.fromObject(resString);
        int id = json.getInt("id");
        if (id < 1) {
            throw new Exception("illegal id returned");
        }
    } catch (JSONException e) {
        /*
         * (1)JSONObject.fromObject?exception???post?
         * (2)id?????????
         *  (????? {"Response":"Not Authorized"} ??HTTP?status?401??)
         */
        throw new Exception("wrong request");
    } finally {
        post.abort();
    }
}

From source file:org.apache.ambari.view.hive.client.Connection.java

private CloseableHttpClient getHttpClient(Boolean useSsl) throws SQLException {
    boolean isCookieEnabled = authParams.get(Utils.HiveAuthenticationParams.COOKIE_AUTH) == null
            || (!Utils.HiveAuthenticationParams.COOKIE_AUTH_FALSE
                    .equalsIgnoreCase(authParams.get(Utils.HiveAuthenticationParams.COOKIE_AUTH)));
    String cookieName = authParams.get(Utils.HiveAuthenticationParams.COOKIE_NAME) == null
            ? Utils.HiveAuthenticationParams.DEFAULT_COOKIE_NAMES_HS2
            : authParams.get(Utils.HiveAuthenticationParams.COOKIE_NAME);
    CookieStore cookieStore = isCookieEnabled ? new BasicCookieStore() : null;
    HttpClientBuilder httpClientBuilder;
    // Request interceptor for any request pre-processing logic
    HttpRequestInterceptor requestInterceptor;
    Map<String, String> additionalHttpHeaders = new HashMap<String, String>();

    // Retrieve the additional HttpHeaders
    for (Map.Entry<String, String> entry : authParams.entrySet()) {
        String key = entry.getKey();

        if (key.startsWith(Utils.HiveAuthenticationParams.HTTP_HEADER_PREFIX)) {
            additionalHttpHeaders.put(key.substring(Utils.HiveAuthenticationParams.HTTP_HEADER_PREFIX.length()),
                    entry.getValue());/*from   w  w  w .ja  v a2  s  .  c om*/
        }
    }
    // Configure http client for kerberos/password based authentication
    if (isKerberosAuthMode()) {
        /**
         * Add an interceptor which sets the appropriate header in the request.
         * It does the kerberos authentication and get the final service ticket,
         * for sending to the server before every request.
         * In https mode, the entire information is encrypted
         */

        Boolean assumeSubject = Utils.HiveAuthenticationParams.AUTH_KERBEROS_AUTH_TYPE_FROM_SUBJECT
                .equals(authParams.get(Utils.HiveAuthenticationParams.AUTH_KERBEROS_AUTH_TYPE));
        requestInterceptor = new HttpKerberosRequestInterceptor(
                authParams.get(Utils.HiveAuthenticationParams.AUTH_PRINCIPAL), host, getServerHttpUrl(useSsl),
                assumeSubject, cookieStore, cookieName, useSsl, additionalHttpHeaders);
    } else {
        /**
         * Add an interceptor to pass username/password in the header.
         * In https mode, the entire information is encrypted
         */
        requestInterceptor = new HttpBasicAuthInterceptor(
                getAuthParamDefault(Utils.HiveAuthenticationParams.AUTH_USER, getUsername()), getPassword(),
                cookieStore, cookieName, useSsl, additionalHttpHeaders);
    }
    // Configure http client for cookie based authentication
    if (isCookieEnabled) {
        // Create a http client with a retry mechanism when the server returns a status code of 401.
        httpClientBuilder = HttpClients.custom()
                .setServiceUnavailableRetryStrategy(new ServiceUnavailableRetryStrategy() {

                    @Override
                    public boolean retryRequest(final HttpResponse response, final int executionCount,
                            final HttpContext context) {
                        int statusCode = response.getStatusLine().getStatusCode();
                        boolean ret = statusCode == 401 && executionCount <= 1;

                        // Set the context attribute to true which will be interpreted by the request interceptor
                        if (ret) {
                            context.setAttribute(Utils.HIVE_SERVER2_RETRY_KEY, Utils.HIVE_SERVER2_RETRY_TRUE);
                        }
                        return ret;
                    }

                    @Override
                    public long getRetryInterval() {
                        // Immediate retry
                        return 0;
                    }
                });
    } else {
        httpClientBuilder = HttpClientBuilder.create();
    }
    // Add the request interceptor to the client builder
    httpClientBuilder.addInterceptorFirst(requestInterceptor);
    // Configure http client for SSL
    if (useSsl) {
        String useTwoWaySSL = authParams.get(Utils.HiveAuthenticationParams.USE_TWO_WAY_SSL);
        String sslTrustStorePath = authParams.get(Utils.HiveAuthenticationParams.SSL_TRUST_STORE);
        String sslTrustStorePassword = authParams.get(Utils.HiveAuthenticationParams.SSL_TRUST_STORE_PASSWORD);
        KeyStore sslTrustStore;
        SSLSocketFactory socketFactory;

        /**
         * The code within the try block throws:
         * 1. SSLInitializationException
         * 2. KeyStoreException
         * 3. IOException
         * 4. NoSuchAlgorithmException
         * 5. CertificateException
         * 6. KeyManagementException
         * 7. UnrecoverableKeyException
         * We don't want the client to retry on any of these, hence we catch all
         * and throw a SQLException.
         */
        try {
            if (useTwoWaySSL != null && useTwoWaySSL.equalsIgnoreCase(Utils.HiveAuthenticationParams.TRUE)) {
                socketFactory = getTwoWaySSLSocketFactory();
            } else if (sslTrustStorePath == null || sslTrustStorePath.isEmpty()) {
                // Create a default socket factory based on standard JSSE trust material
                socketFactory = SSLSocketFactory.getSocketFactory();
            } else {
                // Pick trust store config from the given path
                sslTrustStore = KeyStore.getInstance(Utils.HiveAuthenticationParams.SSL_TRUST_STORE_TYPE);
                try (FileInputStream fis = new FileInputStream(sslTrustStorePath)) {
                    sslTrustStore.load(fis, sslTrustStorePassword.toCharArray());
                }
                socketFactory = new SSLSocketFactory(sslTrustStore);
            }
            socketFactory.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

            final Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
                    .register("https", socketFactory).build();

            httpClientBuilder.setConnectionManager(new BasicHttpClientConnectionManager(registry));
        } catch (Exception e) {
            String msg = "Could not create an https connection to " + getServerHttpUrl(useSsl) + ". "
                    + e.getMessage();
            throw new SQLException(msg, " 08S01", e);
        }
    }
    return httpClientBuilder.build();
}

From source file:ch.admin.hermes.etl.load.cmis.AlfrescoCMISClient.java

/**
 * Liefert einen Http Client wo alle Zertifikate erlaubt sind. Vermeidet Zertifikatfehler.
 * @return DefaultHttpClient//from  w  w  w  .  j a v  a2 s.c o m
 */
private DefaultHttpClient getHttpClient() {
    try {
        HttpParams httpParams = new BasicHttpParams();

        SSLSocketFactory sf = new SSLSocketFactory(new TrustStrategy() {
            public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                return true;
            }
        }, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

        SchemeRegistry registry = new SchemeRegistry();
        registry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory()));
        registry.register(new Scheme("https", 443, sf));

        return new DefaultHttpClient(httpParams);
    } catch (Exception e) {
        return new DefaultHttpClient();
    }
}

From source file:org.workcast.ssoficlient.service.LoginHandler.java

public static ConsumerManager newConsumerManager() throws Exception {
    // Install the all-trusting trust manager SSL Context
    SSLContext sc = SSLPatch.disableSSLCertValidation();

    HttpFetcherFactory hff = new HttpFetcherFactory(sc, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    YadisResolver yr = new YadisResolver(hff);
    RealmVerifierFactory rvf = new RealmVerifierFactory(yr);
    Discovery d = new Discovery(new HtmlResolver(hff), yr, Discovery.getXriResolver());

    ConsumerManager manager = new ConsumerManager(rvf, d, hff);
    manager.setAssociations(new InMemoryConsumerAssociationStore());
    manager.setNonceVerifier(new InMemoryNonceVerifier(5000));
    return manager;
}

From source file:org.fedoraproject.eclipse.packager.api.UploadSourceCommand.java

/**
 * Wrap a basic HttpClient object in an all trusting SSL enabled
 * HttpClient object.//from  ww  w  .j a  v  a2s  .c om
 * 
 * @param base The HttpClient to wrap.
 * @return The SSL wrapped HttpClient.
 * @throws GeneralSecurityException
 * @throws IOException
 */
private HttpClient trustAllSslEnable(HttpClient base) throws GeneralSecurityException {
    // Get an initialized SSL context
    // Create a trust manager that does not validate certificate chains
    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
        @Override
        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return null;
        }

        @Override
        public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) {
        }

        @Override
        public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) {
        }
    } };

    // set up the all-trusting trust manager
    SSLContext sc = SSLContext.getInstance("SSL"); //$NON-NLS-1$
    sc.init(null, trustAllCerts, new java.security.SecureRandom());

    SSLSocketFactory sf = new SSLSocketFactory(sc, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    ClientConnectionManager ccm = base.getConnectionManager();
    SchemeRegistry sr = ccm.getSchemeRegistry();
    Scheme https = new Scheme("https", 443, sf); //$NON-NLS-1$
    sr.register(https);
    return new DefaultHttpClient(ccm, base.getParams());
}

From source file:gov.nih.nci.nbia.StandaloneDMDispatcher.java

private static List<String> connectAndReadFromURL(URL url) {
    List<String> data = null;
    DefaultHttpClient httpClient = null;
    TrustStrategy easyStrategy = new TrustStrategy() {
        @Override/* www  .  j ava 2s. co m*/
        public boolean isTrusted(X509Certificate[] certificate, String authType) throws CertificateException {
            return true;
        }
    };
    try {
        SSLSocketFactory sslsf = new SSLSocketFactory(easyStrategy,
                SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        Scheme httpsScheme = new Scheme("https", 443, sslsf);
        SchemeRegistry schemeRegistry = new SchemeRegistry();
        schemeRegistry.register(httpsScheme);
        schemeRegistry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory()));
        ClientConnectionManager ccm = new ThreadSafeClientConnManager(schemeRegistry);

        HttpParams httpParams = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(httpParams, 50000);
        HttpConnectionParams.setSoTimeout(httpParams, new Integer(12000));
        httpClient = new DefaultHttpClient(ccm, httpParams);
        httpClient.setRoutePlanner(new ProxySelectorRoutePlanner(schemeRegistry, ProxySelector.getDefault()));
        // // Additions by lrt for tcia -
        // // attempt to reduce errors going through a Coyote Point
        // Equalizer load balance switch
        httpClient.getParams().setParameter("http.socket.timeout", new Integer(12000));
        httpClient.getParams().setParameter("http.socket.receivebuffer", new Integer(16384));
        httpClient.getParams().setParameter("http.tcp.nodelay", true);
        httpClient.getParams().setParameter("http.connection.stalecheck", false);
        // // end lrt additions

        HttpPost httpPostMethod = new HttpPost(url.toString());

        List<BasicNameValuePair> postParams = new ArrayList<BasicNameValuePair>();
        postParams.add(new BasicNameValuePair(osParam, os));
        UrlEncodedFormEntity query = new UrlEncodedFormEntity(postParams);
        httpPostMethod.setEntity(query);
        HttpResponse response = httpClient.execute(httpPostMethod);
        int responseCode = response.getStatusLine().getStatusCode();

        if (responseCode == HttpStatus.SC_OK) {
            InputStream inputStream = response.getEntity().getContent();
            data = IOUtils.readLines(inputStream);
        } else {
            JOptionPane.showMessageDialog(null, "Incorrect response from server: " + responseCode);
        }

    } catch (java.net.ConnectException e) {
        String note = "Connection error 1 while connecting to " + url.toString() + ":\n" + getProxyInfo();
        //+ checkListeningPort("127.0.0.1", 8888);
        printStackTraceToDialog(note, e);
        //JOptionPane.showMessageDialog(null, "Connection error 1: " + e.getMessage());
        e.printStackTrace();
    } catch (MalformedURLException e) {
        String note = "Connection error 2 while connecting to " + url.toString() + ":\n";
        printStackTraceToDialog(note, e);
        //JOptionPane.showMessageDialog(null, "Connection error 2: " + e.getMessage());
        e.printStackTrace();
    } catch (IOException e) {
        String note = "Connection error 3 while connecting to " + url.toString() + ":\n";
        printStackTraceToDialog(note, e);
        //JOptionPane.showMessageDialog(null, "Connection error 3: " + e.getMessage());
        e.printStackTrace();
    } catch (KeyManagementException e) {
        String note = "Connection error 4 while connecting to " + url.toString() + ":\n";
        printStackTraceToDialog(note, e);
        //JOptionPane.showMessageDialog(null, "Connection error 4: " + e.getMessage());
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        String note = "Connection error 5 while connecting to " + url.toString() + ":\n";
        printStackTraceToDialog(note, e);
        //JOptionPane.showMessageDialog(null, "Connection error 5: " + e.getMessage());
        e.printStackTrace();
    } catch (KeyStoreException e) {
        String note = "Connection error 6 while connecting to " + url.toString() + ":\n";
        printStackTraceToDialog(note, e);
        //JOptionPane.showMessageDialog(null, "Connection error 6: " + e.getMessage());
        e.printStackTrace();
    } catch (UnrecoverableKeyException e) {
        String note = "Connection error 7 while connecting to " + url.toString() + ":\n";
        printStackTraceToDialog(note, e);
        //JOptionPane.showMessageDialog(null, "Connection error 7: " + e.getMessage());
        e.printStackTrace();
    } finally {
        if (httpClient != null) {
            httpClient.getConnectionManager().shutdown();
        }
    }
    return data;
}