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.apache.brooklyn.launcher.BrooklynWebServerTest.java

private void verifyHttpsFromConfig(BrooklynProperties brooklynProperties) throws Exception {
    webServer = new BrooklynWebServer(MutableMap.of(), newManagementContext(brooklynProperties));
    webServer.start();/*from   w  w  w  .  java2 s . c o m*/

    try {
        KeyStore keyStore = load("client.ks", "password");
        KeyStore trustStore = load("client.ts", "password");
        SSLSocketFactory socketFactory = new SSLSocketFactory(SSLSocketFactory.TLS, keyStore, "password",
                trustStore, (SecureRandom) null, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

        HttpToolResponse response = HttpTool.execAndConsume(HttpTool.httpClientBuilder()
                .port(webServer.getActualPort()).https(true).socketFactory(socketFactory).build(),
                new HttpGet(webServer.getRootUrl()));
        assertEquals(response.getResponseCode(), 200);
    } finally {
        webServer.stop();
    }
}

From source file:com.dumiduh.das.AnalyticsAPIInvoker.java

private String invoke(String url, String username, String pwd, String type) {
    TrustStrategyExt strategy = new TrustStrategyExt();

    String jsonString = "";
    try {/* ww w.j a v  a  2  s  .  com*/
        SSLSocketFactory sf = new SSLSocketFactory(strategy, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        SchemeRegistry registry = new SchemeRegistry();
        registry.register(new Scheme("https", Integer.parseInt(port), sf));
        ClientConnectionManager ccm = new PoolingClientConnectionManager(registry);

        DefaultHttpClient client = new DefaultHttpClient(ccm);
        HttpGet get = new HttpGet(url);
        String header = "Basic " + getBase64EncodedToken(username, pwd);
        get.setHeader("Authorization", header);

        HttpResponse resp = client.execute(get);
        if (type.equals("body")) {
            BufferedReader rd = new BufferedReader(new InputStreamReader(resp.getEntity().getContent()));

            StringBuffer result = new StringBuffer();
            String line = "";
            while ((line = rd.readLine()) != null) {
                result.append(line);
            }
            jsonString = result.toString();
        } else if (type.equals("header")) {
            StringBuffer result = new StringBuffer();
            Header[] headers = resp.getAllHeaders();
            for (Header h : headers) {

                result.append(h.getName() + " : " + h.getValue());
            }
            result.append("status code : " + resp.getStatusLine().getStatusCode());
            jsonString = result.toString();
        }

        client.close();

    } catch (NoSuchAlgorithmException ex) {
        Logger.getLogger(AnalyticsAPIInvoker.class.getName()).log(Level.SEVERE, null, ex);
    } catch (KeyManagementException ex) {
        Logger.getLogger(AnalyticsAPIInvoker.class.getName()).log(Level.SEVERE, null, ex);
    } catch (KeyStoreException ex) {
        Logger.getLogger(AnalyticsAPIInvoker.class.getName()).log(Level.SEVERE, null, ex);
    } catch (UnrecoverableKeyException ex) {
        Logger.getLogger(AnalyticsAPIInvoker.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(AnalyticsAPIInvoker.class.getName()).log(Level.SEVERE, null, ex);
    } catch (NumberFormatException ex) {
        Logger.getLogger(AnalyticsAPIInvoker.class.getName()).log(Level.SEVERE, null, ex);
    }

    return jsonString;
}

From source file:li.klass.fhem.fhem.FHEMWEBConnection.java

private DefaultHttpClient createNewHTTPClient(int connectionTimeout, int socketTimeout) {
    try {//ww  w  .j  a v  a2  s .  c o  m
        KeyStore trustStore;
        SSLSocketFactory socketFactory;

        trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(null, null);

        socketFactory = new CustomSSLSocketFactory(trustStore);
        socketFactory.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

        HttpParams params = new BasicHttpParams();
        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
        HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
        HttpConnectionParams.setConnectionTimeout(params, connectionTimeout);
        HttpConnectionParams.setSoTimeout(params, socketTimeout);

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

        ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);

        return new DefaultHttpClient(ccm, params);
    } catch (Exception e) {
        return new DefaultHttpClient();
    }
}

From source file:com.zrlh.llkc.funciton.Http_Utility.java

public static HttpClient getNewHttpClient(Context context) {
    try {/*  ww  w. j a  v a2 s .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();

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

        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, Http_Utility.SET_CONNECTION_TIMEOUT);
        HttpConnectionParams.setSoTimeout(params, Http_Utility.SET_SOCKET_TIMEOUT);
        HttpClient client = new DefaultHttpClient(ccm, params);

        WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
        WifiInfo info = wifiManager.getConnectionInfo();
        if (!wifiManager.isWifiEnabled() || -1 == info.getNetworkId()) {
            // ??APN?
            Uri uri = Uri.parse("content://telephony/carriers/preferapn");
            Cursor mCursor = context.getContentResolver().query(uri, null, null, null, null);
            if (mCursor != null && mCursor.moveToFirst()) {
                // ???
                String proxyStr = mCursor.getString(mCursor.getColumnIndex("proxy"));
                if (proxyStr != null && proxyStr.trim().length() > 0) {
                    HttpHost proxy = new HttpHost(proxyStr, 80);
                    client.getParams().setParameter(ConnRouteParams.DEFAULT_PROXY, proxy);
                }
                mCursor.close();
            }
        }
        return client;
    } catch (Exception e) {
        return new DefaultHttpClient();
    }
}

From source file:org.opcfoundation.ua.examples.ClientServerExample.java

public MyServerExample(Application application)
        throws CertificateException, IOException, UnrecoverableKeyException, NoSuchAlgorithmException,
        KeyStoreException, URISyntaxException, ServiceResultException {
    super(application);
    // Add method service set
    addServiceHandler(this);

    // Add Client Application Instance Certificate validator - Accept them all (for now)
    application.getOpctcpSettings().setCertificateValidator(CertificateValidator.ALLOW_ALL);
    application.getHttpsSettings().setCertificateValidator(CertificateValidator.ALLOW_ALL);

    // The HTTPS SecurityPolicies are defined separate from the endpoint securities
    application.getHttpsSettings().setHttpsSecurityPolicies(HttpsSecurityPolicy.ALL);

    // Peer verifier
    application.getHttpsSettings().setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

    // Load Servers's Application Instance Certificate...
    KeyPair myServerApplicationInstanceCertificate = ExampleKeys.getCert("ClientServerExample");
    application.addApplicationInstanceCertificate(myServerApplicationInstanceCertificate);
    // ...and HTTPS certificate
    KeyPair myHttpsCertificate = ExampleKeys.getHttpsCert("ClientServerExample");
    application.getHttpsSettings().setKeyPair(myHttpsCertificate);

    // Add User Token Policies
    addUserTokenPolicy(UserTokenPolicy.ANONYMOUS);
    addUserTokenPolicy(UserTokenPolicy.SECURE_USERNAME_PASSWORD);

    // Create an endpoint for each network interface
    String hostname = EndpointUtil.getHostname();
    String bindAddress, endpointAddress;
    for (String addr : EndpointUtil.getInetAddressNames()) {
        bindAddress = "https://" + addr + ":8443/UAExample";
        endpointAddress = "https://" + hostname + ":8443/UAExample";
        System.out.println(endpointAddress + " bound at " + bindAddress);
        // The HTTPS ports are using NONE OPC security 
        bind(bindAddress, endpointAddress, SecurityMode.NONE);

        bindAddress = "opc.tcp://" + addr + ":8666/UAExample";
        endpointAddress = "opc.tcp://" + hostname + ":8666/UAExample";
        System.out.println(endpointAddress + " bound at " + bindAddress);
        bind(bindAddress, endpointAddress, SecurityMode.ALL);
    }/*from  w  ww.  j  av  a 2s .  c  o m*/

    //////////////////////////////////////

}

From source file:org.esxx.js.protocol.HTTPHandler.java

private static synchronized ClientConnectionManager getConnectionManager() {
    if (connectionManager == null) {
        SchemeRegistry sr = new SchemeRegistry();
        sr.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
        //      sr.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));

        try {/*from   w  w  w . ja  va2 s. c o  m*/
            SSLContext sslcontext = SSLContext.getInstance(SSLSocketFactory.TLS);
            sslcontext.init(null, new TrustManager[] { new X509TrustManager() {
                @Override
                public void checkServerTrusted(X509Certificate[] chain, String auth) {
                }

                @Override
                public X509Certificate[] getAcceptedIssuers() {
                    return new X509Certificate[0];
                }

                @Override
                public void checkClientTrusted(X509Certificate[] certs, String auth) {
                }
            } }, new java.security.SecureRandom());

            SSLSocketFactory ssf = new SSLSocketFactory(sslcontext, null);
            ssf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
            sr.register(new Scheme("https", ssf, 443));
        } catch (Exception ex) {
            ex.printStackTrace();
        }

        connectionManager = new ThreadSafeClientConnManager(getHttpParams(), sr);
    }

    return connectionManager;
}

From source file:com.prasanna.android.http.SecureHttpHelper.java

protected HttpClient createSecureHttpClient() {
    try {// w  ww .j  a va  2 s .c  o  m
        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(null, null);

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

        HttpParams params = new BasicHttpParams();
        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
        HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
        SchemeRegistry schemeRegistry = new SchemeRegistry();
        schemeRegistry.register(new Scheme(SCHEME_HTTPS, sf, HTTPS_PORT));
        schemeRegistry.register(new Scheme(SCHEME_HTTP, PlainSocketFactory.getSocketFactory(), HTTP_PORT));

        return new DefaultHttpClient(new SingleClientConnManager(params, schemeRegistry), params);
    } catch (KeyManagementException e) {
        LogWrapper.e(TAG, e.getMessage());
    } catch (UnrecoverableKeyException e) {
        LogWrapper.e(TAG, e.getMessage());
    } catch (KeyStoreException e) {
        LogWrapper.e(TAG, e.getMessage());
    } catch (NoSuchAlgorithmException e) {
        LogWrapper.e(TAG, e.getMessage());
    } catch (CertificateException e) {
        LogWrapper.e(TAG, e.getMessage());
    } catch (IOException e) {
        LogWrapper.e(TAG, e.getMessage());
    }

    throw new ClientException(ClientErrorCode.HTTP_REQ_ERROR);
}

From source file:wsattacker.plugin.dos.dosExtension.requestSender.RequestSenderImpl.java

private String sendRequestHttpClient(RequestObject requestObject) {

    // get Post Request
    HttpPost post = this.createHttpPostMethod(requestObject);

    // set afterReceive to default value to handle missing responses
    afterReceive = 0;/* w  ww.j  a v  a2s .  c  om*/

    // Get HTTP client and execute request
    try {
        URL url = new URL(requestObject.getEndpoint());
        String protocol = url.getProtocol();

        HttpClient httpClient;
        if (protocol.equalsIgnoreCase("https")) {
            SSLContext ctx = SSLContext.getInstance("TLS");
            X509TrustManager tm = new X509TrustManager() {
                @Override
                public void checkClientTrusted(X509Certificate[] xcs, String string)
                        throws CertificateException {
                }

                @Override
                public void checkServerTrusted(X509Certificate[] xcs, String string)
                        throws CertificateException {
                }

                @Override
                public X509Certificate[] getAcceptedIssuers() {
                    return null;
                }
            };
            ctx.init(null, new TrustManager[] { tm }, null);

            SSLSocketFactory sf = new SSLSocketFactory(ctx, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
            Scheme httpsScheme = new Scheme("https", url.getPort(), sf);
            SchemeRegistry schemeRegistry = new SchemeRegistry();
            schemeRegistry.register(httpsScheme);

            // apache HttpClient version >4.2 should use
            // BasicClientConnectionManager
            ClientConnectionManager cm = new SingleClientConnManager(schemeRegistry);

            httpClient = new DefaultHttpClient(cm);
        } else {
            httpClient = new DefaultHttpClient();
        }

        httpClient.getParams().setParameter("http.socket.timeout", TIMEOUT);
        httpClient.getParams().setParameter("http.connection.timeout", TIMEOUT);
        httpClient.getParams().setParameter("http.connection-manager.max-per-host", TIMEOUT);
        httpClient.getParams().setParameter("http.connection-manager.max-total", new Integer(3000));
        // > params.setDefaultMaxConnectionsPerHost(3000);
        // > params.setMaxTotalConnections(3000);

        beforeSend = System.nanoTime();

        HttpResponse response = httpClient.execute(post);
        StringWriter writer = new StringWriter();
        IOUtils.copy(response.getEntity().getContent(), writer, "UTF-8");
        responseString = writer.toString();

        afterReceive = System.nanoTime();
        // System.out.println("Response status code: " + result);
        // System.out.println("Response body: " + responseString);
    } catch (IOException ex) {
        // Logger.getLogger(RequestSender.class.getName()).log(Level.SEVERE,
        // null, ex);
        System.out.println("--RequestSender - IO Exception: " + ex.getMessage());

        // ex.printStackTrace();
    } catch (Exception e) {
        // Request timed out!?
        System.out.println("--RequestSender - unexpected Exception: " + e.getMessage());
    } finally {
        // Release current connection to the connection pool
        // post.releaseConnection();

        if (responseString == null) {
            responseString = "";
        }

        // Set afterReceive to beforeSend if afterReceive is 0 so that there 
        // is no huge negative response time when the web service doesn't answer
        if (afterReceive == 0) {
            afterReceive = beforeSend;
        }
    }

    return responseString;
}

From source file:org.wso2.carbon.dynamic.client.web.app.registration.util.RemoteDCRClient.java

private static DefaultHttpClient getHTTPSClient() {
    DefaultHttpClient httpClient = new DefaultHttpClient();
    // Setup the HTTPS settings to accept any certificate.
    HostnameVerifier hostnameVerifier = org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;

    SchemeRegistry registry = new SchemeRegistry();
    SSLSocketFactory socketFactory = SSLSocketFactory.getSocketFactory();
    socketFactory.setHostnameVerifier((X509HostnameVerifier) hostnameVerifier);
    registry.register(new Scheme(
            DynamicClientWebAppRegistrationConstants.RemoteServiceProperties.DYNAMIC_CLIENT_SERVICE_PROTOCOL,
            socketFactory, getServerHTTPSPort()));
    SingleClientConnManager mgr = new SingleClientConnManager(httpClient.getParams(), registry);
    httpClient = new DefaultHttpClient(mgr, httpClient.getParams());

    // Set verifier
    HttpsURLConnection.setDefaultHostnameVerifier(hostnameVerifier);
    return httpClient;
}

From source file:be.fedict.eid.idp.sp.protocol.openid.AuthenticationRequestServlet.java

/**
 * {@inheritDoc}/*from w ww .  jav  a2  s  . c o m*/
 */
@Override
public void init(ServletConfig config) throws ServletException {

    this.userIdentifier = config.getInitParameter(USER_IDENTIFIER_PARAM);
    this.spDestination = config.getInitParameter(SP_DESTINATION_PARAM);
    this.spDestinationPage = config.getInitParameter(SP_DESTINATION_PAGE_PARAM);
    this.languages = config.getInitParameter(LANGUAGES_PARAM);
    this.authenticationRequestServiceLocator = new ServiceLocator<AuthenticationRequestService>(
            AUTHN_REQUEST_SERVICE_PARAM, config);

    // validate necessary configuration params
    if (null == this.userIdentifier && !this.authenticationRequestServiceLocator.isConfigured()) {
        throw new ServletException("need to provide either " + USER_IDENTIFIER_PARAM + " or "
                + AUTHN_REQUEST_SERVICE_PARAM + "(Class) init-params");
    }

    if (null == this.spDestination && null == this.spDestinationPage
            && !this.authenticationRequestServiceLocator.isConfigured()) {
        throw new ServletException("need to provide either " + SP_DESTINATION_PARAM + " or "
                + SP_DESTINATION_PAGE_PARAM + " or " + AUTHN_REQUEST_SERVICE_PARAM + "(Class) init-param");
    }

    // SSL configuration
    String trustServer = config.getInitParameter(TRUST_SERVER_PARAM);
    if (null != trustServer) {
        this.trustServer = Boolean.parseBoolean(trustServer);
    }
    X509Certificate serverCertificate = null;
    if (this.authenticationRequestServiceLocator.isConfigured()) {
        AuthenticationRequestService service = this.authenticationRequestServiceLocator.locateService();
        serverCertificate = service.getServerCertificate();
    }

    if (this.trustServer) {

        LOG.warn("Trusting all SSL server certificates!");
        try {
            OpenIDSSLSocketFactory.installAllTrusted();
        } catch (Exception e) {
            throw new ServletException("could not install OpenID SSL Socket Factory: " + e.getMessage(), e);
        }
    } else if (null != serverCertificate) {

        LOG.info("Trusting specified SSL certificate: " + serverCertificate);
        try {
            OpenIDSSLSocketFactory.install(serverCertificate);
        } catch (Exception e) {
            throw new ServletException("could not install OpenID SSL Socket Factory: " + e.getMessage(), e);
        }
    }

    ServletContext servletContext = config.getServletContext();
    this.consumerManager = (ConsumerManager) servletContext.getAttribute(CONSUMER_MANAGER_ATTRIBUTE);

    if (null == this.consumerManager) {
        try {
            if (this.trustServer || null != serverCertificate) {

                TrustManager trustManager;
                if (this.trustServer) {
                    trustManager = new OpenIDTrustManager();
                } else {
                    trustManager = new OpenIDTrustManager(serverCertificate);
                }

                SSLContext sslContext = SSLContext.getInstance("SSL");
                TrustManager[] trustManagers = { trustManager };
                sslContext.init(null, trustManagers, null);
                HttpFetcherFactory httpFetcherFactory = new HttpFetcherFactory(sslContext,
                        SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
                YadisResolver yadisResolver = new YadisResolver(httpFetcherFactory);
                RealmVerifierFactory realmFactory = new RealmVerifierFactory(yadisResolver);
                HtmlResolver htmlResolver = new HtmlResolver(httpFetcherFactory);
                XriResolver xriResolver = Discovery.getXriResolver();
                Discovery discovery = new Discovery(htmlResolver, yadisResolver, xriResolver);
                this.consumerManager = new ConsumerManager(realmFactory, discovery, httpFetcherFactory);

            } else {
                this.consumerManager = new ConsumerManager();
            }
        } catch (Exception e) {
            throw new ServletException("could not init OpenID ConsumerManager");
        }
        servletContext.setAttribute(CONSUMER_MANAGER_ATTRIBUTE, this.consumerManager);
    }
}