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

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

Introduction

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

Prototype

public void setHostnameVerifier(final X509HostnameVerifier hostnameVerifier) 

Source Link

Usage

From source file:org.openiot.gsn.http.rest.PushRemoteWrapper.java

public boolean initialize() {

    try {//from www. j  a va2s.co  m
        initParams = new RemoteWrapperParamParser(getActiveAddressBean(), true);
        uid = Math.random();

        postParameters = new ArrayList<NameValuePair>();
        postParameters.add(new BasicNameValuePair(PushDelivery.NOTIFICATION_ID_KEY, Double.toString(uid)));
        postParameters.add(
                new BasicNameValuePair(PushDelivery.LOCAL_CONTACT_POINT, initParams.getLocalContactPoint()));
        // Init the http client
        if (initParams.isSSLRequired()) {
            KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
            trustStore.load(new FileInputStream(new File("conf/servertestkeystore")),
                    Main.getContainerConfig().getSSLKeyStorePassword().toCharArray());
            SSLSocketFactory socketFactory = new SSLSocketFactory(trustStore);
            socketFactory.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
            int sslPort = Main.getContainerConfig().getSSLPort() > 0 ? Main.getContainerConfig().getSSLPort()
                    : ContainerConfig.DEFAULT_SSL_PORT;
            Scheme sch = new Scheme("https", socketFactory, sslPort);
            httpclient.getConnectionManager().getSchemeRegistry().register(sch);
        }
        Scheme plainsch = new Scheme("http", PlainSocketFactory.getSocketFactory(),
                Main.getContainerConfig().getContainerPort());
        httpclient.getConnectionManager().getSchemeRegistry().register(plainsch);
        //
        lastReceivedTimestamp = initParams.getStartTime();
        structure = registerAndGetStructure();
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
        NotificationRegistry.getInstance().removeNotification(uid);
        return false;
    }

    return true;
}

From source file:org.openiot.gsn.http.rest.RestRemoteWrapper.java

public boolean initialize() {
    try {/*w ww  . j  a va2  s  .c  o  m*/
        initParams = new RemoteWrapperParamParser(getActiveAddressBean(), false);
        httpclient = new DefaultHttpClient(getHttpClientParams(initParams.getTimeout()));
        // Init the http client
        if (initParams.isSSLRequired()) {
            KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
            trustStore.load(new FileInputStream(new File("conf/servertestkeystore")),
                    Main.getContainerConfig().getSSLKeyStorePassword().toCharArray());
            SSLSocketFactory socketFactory = new SSLSocketFactory(trustStore);
            socketFactory.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
            int sslPort = Main.getContainerConfig().getSSLPort() > 0 ? Main.getContainerConfig().getSSLPort()
                    : ContainerConfig.DEFAULT_SSL_PORT;
            Scheme sch = new Scheme("https", socketFactory, sslPort);
            httpclient.getConnectionManager().getSchemeRegistry().register(sch);
        }
        Scheme plainsch = new Scheme("http", PlainSocketFactory.getSocketFactory(),
                Main.getContainerConfig().getContainerPort());
        httpclient.getConnectionManager().getSchemeRegistry().register(plainsch);
        //
        lastReceivedTimestamp = initParams.getStartTime();
        structure = connectToRemote();
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
        return false;
    }
    return true;
}

From source file:android.net.http.AbstractProxyTest.java

public void testConnectToHttps() throws Exception {
    TestSSLContext testSSLContext = TestSSLContext.create();

    server.useHttps(testSSLContext.serverContext.getSocketFactory(), false);
    server.enqueue(new MockResponse().setResponseCode(200).setBody("this response comes via HTTPS"));
    server.play();/*  ww  w.jav a  2s.c o  m*/

    HttpClient httpClient = newHttpClient();

    SSLSocketFactory sslSocketFactory = newSslSocketFactory(testSSLContext);
    sslSocketFactory.setHostnameVerifier(new AllowAllHostnameVerifier());
    httpClient.getConnectionManager().getSchemeRegistry()
            .register(new Scheme("https", sslSocketFactory, server.getPort()));

    HttpResponse response = httpClient.execute(new HttpGet("https://localhost:" + server.getPort() + "/foo"));
    assertEquals("this response comes via HTTPS", contentToString(response));

    RecordedRequest request = server.takeRequest();
    assertEquals("GET /foo HTTP/1.1", request.getRequestLine());
}

From source file:org.energy_home.jemma.utils.rest.RestClient.java

private RestClient() {
    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory()));
    SSLSocketFactory sslSocketFactory = SSLSocketFactory.getSocketFactory();
    // allow working with all hostname server (hostname verification default turned off)
    sslSocketFactory.setHostnameVerifier(new AllowAllHostnameVerifier());
    schemeRegistry.register(new Scheme("https", 443, sslSocketFactory));

    ThreadSafeClientConnManager connectionManager = new ThreadSafeClientConnManager(schemeRegistry);
    // TODO: check for final values
    // Decrease max total connection to 10 (default is 20)
    connectionManager.setMaxTotal(10);//  w  w w . j  av a 2  s .c o m
    // Increase default max connection per route to 5 (default is 2)
    connectionManager.setDefaultMaxPerRoute(10);
    // // Increase max connections for localhost:80 to 50
    // HttpHost localhost = new HttpHost("locahost", 80);
    // cm.setMaxForRoute(new HttpRoute(localhost), 50);
    // // Increase max connections for a specific host to 10
    // connectionManager.setMaxForRoute(new HttpRoute(httpHost), 10);

    httpClient = new DefaultHttpClient(connectionManager);
    httpClient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_0);
    // Default to HTTP 1.0
    httpClient.getParams().setParameter(CoreProtocolPNames.HTTP_CONTENT_CHARSET, "UTF-8");
    // The time it takes to open TCP connection.
    // httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT,
    // 15000);
    // Timeout when server does not send data.
    httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, SO_TIMEOUT);

    // Some tuning that is not required for bit tests.
    // httpClient.getParams().setParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK,
    // false);
    // httpClient.getParams().setParameter(CoreConnectionPNames.TCP_NODELAY,
    // true);
    httpContext = new BasicHttpContext();
}

From source file:android.net.http.AbstractProxyTest.java

private void testConnectViaHttpProxyToHttps(ProxyConfig proxyConfig) throws Exception {
    TestSSLContext testSSLContext = TestSSLContext.create();

    server.useHttps(testSSLContext.serverContext.getSocketFactory(), true);
    server.enqueue(new MockResponse().setSocketPolicy(SocketPolicy.UPGRADE_TO_SSL_AT_END).clearHeaders());
    server.enqueue(new MockResponse().setResponseCode(200).setBody("this response comes via a secure proxy"));
    server.play();/*from w  w  w.j a v  a2  s .c o  m*/

    HttpClient httpProxyClient = newHttpClient();
    SSLSocketFactory sslSocketFactory = newSslSocketFactory(testSSLContext);
    sslSocketFactory.setHostnameVerifier(new AllowAllHostnameVerifier());
    httpProxyClient.getConnectionManager().getSchemeRegistry()
            .register(new Scheme("https", sslSocketFactory, 443));

    HttpGet request = new HttpGet("https://android.com/foo");
    proxyConfig.configure(server, httpProxyClient, request);

    HttpResponse response = httpProxyClient.execute(request);
    assertEquals("this response comes via a secure proxy", contentToString(response));

    RecordedRequest connect = server.takeRequest();
    assertEquals("Connect line failure on proxy " + proxyConfig, "CONNECT android.com:443 HTTP/1.1",
            connect.getRequestLine());
    assertContains(connect.getHeaders(), "Host: android.com");

    RecordedRequest get = server.takeRequest();
    assertEquals("GET /foo HTTP/1.1", get.getRequestLine());
    assertContains(get.getHeaders(), "Host: android.com");
}

From source file:iristk.speech.nuancecloud.NuanceCloudSynthesizer.java

private HttpClient getHttpClient() throws NoSuchAlgorithmException, KeyManagementException {
    // Standard HTTP parameters
    HttpParams params = new BasicHttpParams();
    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setContentCharset(params, "UTF-8");
    HttpProtocolParams.setUseExpectContinue(params, false);

    // Initialize the HTTP client
    httpclient = new DefaultHttpClient(params);

    // Initialize/setup SSL
    TrustManager easyTrustManager = new X509TrustManager() {
        @Override//from ww w .  j  ava 2s.c o m
        public void checkClientTrusted(java.security.cert.X509Certificate[] arg0, String arg1)
                throws java.security.cert.CertificateException {
            // TODO Auto-generated method stub
        }

        @Override
        public void checkServerTrusted(java.security.cert.X509Certificate[] arg0, String arg1)
                throws java.security.cert.CertificateException {
            // TODO Auto-generated method stub
        }

        @Override
        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            // TODO Auto-generated method stub
            return null;
        }
    };

    SSLContext sslcontext = SSLContext.getInstance("TLS");
    sslcontext.init(null, new TrustManager[] { easyTrustManager }, null);
    SSLSocketFactory sf = new SSLSocketFactory(sslcontext);
    sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    Scheme sch = new Scheme("https", sf, PORT); // PORT = 443
    httpclient.getConnectionManager().getSchemeRegistry().register(sch);

    // Return the initialized instance of our httpclient
    return httpclient;
}

From source file:info.semanticsoftware.semassist.android.activity.AuthenticationActivity.java

private String authenicate(String username, String password) {
    String uri = serverURL + "/user";
    Log.d(Constants.TAG, uri);/*from  w  w w .j  av a 2  s  . c om*/
    String request = "<authenticate><username>" + username + "</username><password>" + password
            + "</password></authenticate>";
    Representation representation = new StringRepresentation(request, MediaType.APPLICATION_XML);
    String serverResponse = null;

    if (serverURL.indexOf("https") < 0) {
        Log.i(TAG, "Sending authentication request to " + uri);
        Representation response = new ClientResource(uri).post(representation);
        try {
            StringWriter writer = new StringWriter();
            response.write(writer);
            serverResponse = writer.toString();
            Log.i(TAG, "Authentication response: " + serverResponse);
        } catch (Exception e) {
            e.printStackTrace();
        }
    } else {
        try {
            Log.i(TAG, "Sending authentication request to " + uri);
            HostnameVerifier hostnameVerifier = org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;
            DefaultHttpClient client = new DefaultHttpClient();

            SchemeRegistry registry = new SchemeRegistry();
            final KeyStore ks = KeyStore.getInstance("BKS");
            // NOTE: the keystore must have been generated with BKS 146 and not later
            final InputStream in = getApplicationContext().getResources()
                    .openRawResource(R.raw.clientkeystorenew);
            try {
                ks.load(in, getString(R.string.keystorePassword).toCharArray());
            } finally {
                in.close();
            }

            SSLSocketFactory socketFactory = new CustomSSLSocketFactory(ks);
            socketFactory.setHostnameVerifier((X509HostnameVerifier) hostnameVerifier);
            registry.register(new Scheme("https", socketFactory, 443));
            SingleClientConnManager mgr = new SingleClientConnManager(client.getParams(), registry);
            DefaultHttpClient httpClient = new DefaultHttpClient(mgr, client.getParams());

            // Set verifier
            HttpsURLConnection.setDefaultHostnameVerifier(hostnameVerifier);

            HttpPost post = new HttpPost(uri);
            post.setEntity(new StringEntity(representation.getText()));

            HttpResponse response = httpClient.execute(post);
            HttpEntity entity = response.getEntity();
            InputStream inputstream = entity.getContent();
            InputStreamReader inputstreamreader = new InputStreamReader(inputstream);
            BufferedReader bufferedreader = new BufferedReader(inputstreamreader);

            String string = null;
            while ((string = bufferedreader.readLine()) != null) {
                serverResponse += string;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    return serverResponse;
}

From source file:com.base.net.volley.toolbox.HttpClientStack.java

/**
 * https?//from   ww w.j a va2  s .co  m
 * @param client
 */
private void setClientHttps(HttpClient client) {

    try {
        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(null, null);
        SSLSocketFactory sf = new SSLSocketFactoryEx(trustStore);
        sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); // ??
        ClientConnectionManager conManager = client.getConnectionManager();
        SchemeRegistry schReg = conManager.getSchemeRegistry();
        if (schReg == null) {
            schReg = new SchemeRegistry();
        }
        schReg.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
        schReg.register(new Scheme("https", sf, 443));

    } catch (KeyStoreException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (CertificateException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (KeyManagementException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (UnrecoverableKeyException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

From source file:net.sourceforge.jwbf.mediawiki.live.LoginTest.java

private AbstractHttpClient getSSLFakeHttpClient() throws NoSuchAlgorithmException, KeyManagementException {
    SSLContext sslContext = SSLContext.getInstance("SSL");
    sslContext.init(null, new TrustManager[] { new X509TrustManager() {
        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }//from  w w  w .ja va 2s  .  com

        public void checkClientTrusted(X509Certificate[] certs, String authType) {
        }

        public void checkServerTrusted(X509Certificate[] certs, String authType) {
        }
    } }, new SecureRandom());

    SSLSocketFactory sf = new SSLSocketFactory(sslContext);
    sf.setHostnameVerifier(new X509HostnameVerifier() {

        public boolean verify(String hostname, SSLSession session) {
            return true;
        }

        public void verify(String host, String[] cns, String[] subjectAlts) throws SSLException {
        }

        public void verify(String host, X509Certificate cert) throws SSLException {
        }

        public void verify(String host, SSLSocket ssl) throws IOException {
        }
    });
    Scheme httpsScheme = new Scheme("https", sf, 443);
    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(httpsScheme);

    HttpParams params = new BasicHttpParams();

    ClientConnectionManager cm = new SingleClientConnManager(params, schemeRegistry);

    DefaultHttpClient httpClient = new DefaultHttpClient(cm, params);
    return httpClient;
}

From source file:srl.distributed.client.Client.java

private DefaultHttpClient getNewHttpClient() {
    try {// w  ww  . j  av a2 s  .  c  o m
        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(null, null);

        SSLSocketFactory sf = new InsecureSSLSocketFactory(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);

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