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

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

Introduction

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

Prototype

public SSLSocketFactory(final SSLContext sslContext) 

Source Link

Usage

From source file:org.eclipse.lyo.oslc4j.bugzilla.utils.BugzillaHttpClient.java

private static HttpClient getHttpClient() {
    SSLContext sc = getTrustingSSLContext();
    SchemeSocketFactory sf = new SSLSocketFactory(sc);

    Scheme scheme = new Scheme("https", 443, sf);
    SchemeRegistry schemeRegistry = new SchemeRegistry();

    schemeRegistry.register(scheme);/*from  ww w.  j ava 2s.c  om*/

    sf = PlainSocketFactory.getSocketFactory();
    scheme = new Scheme("http", 80, sf);

    schemeRegistry.register(scheme);

    ClientConnectionManager clientConnectionManager = new PoolingClientConnectionManager(schemeRegistry);
    HttpParams clientParams = new BasicHttpParams();

    clientParams.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, TIMEOUT);
    clientParams.setParameter(CoreConnectionPNames.SO_TIMEOUT, TIMEOUT);
    clientParams.setParameter(ClientPNames.HANDLE_REDIRECTS, true);

    return new DefaultHttpClient(clientConnectionManager, clientParams);
}

From source file:org.eclipse.thym.core.engine.internal.cordova.NpmBasedEngineRepoProvider.java

private InputStream getRemoteJSonStream(String url) throws IOException {
    try {//from  www. ja  v a  2  s.  c  o m
        // SSLSocketFactory to patch HTTPClient's that are earlier than 4.3.2
        // to enable SNI support.
        SSLSocketFactory factory = new SSLSocketFactory(SSLContext.getDefault()) {
            @Override
            public Socket createSocket() throws IOException {
                return SocketFactory.getDefault().createSocket();
            }

            @Override
            public Socket createSocket(HttpParams params) throws IOException {
                return SocketFactory.getDefault().createSocket();
            }
        };
        DefaultHttpClient client = new DefaultHttpClient();
        HttpUtil.setupProxy(client);
        client.getConnectionManager().getSchemeRegistry().register(new Scheme("https", 443, factory));
        HttpGet get = new HttpGet(url);
        HttpResponse response = client.execute(get);
        HttpEntity entity = response.getEntity();
        return entity.getContent();
    } catch (NoSuchAlgorithmException e) {
        HybridCore.log(IStatus.ERROR, "Error creating the SSL Factory ", e);
    }
    return null;
}

From source file:org.eclipse.dirigible.ide.common.io.ProxyUtils.java

public static HttpClient getHttpClient(boolean trustAll) {
    HttpClient httpClient = null;//from ww w  . j  a v a 2  s.c o m

    // Local case only
    // try {
    // loadLocalBuildProxy();
    // } catch (IOException e) {
    // logger.error(e.getMessage(), e);
    // }

    if (trustAll) {
        try {
            SchemeSocketFactory plainSocketFactory = PlainSocketFactory.getSocketFactory();
            SchemeSocketFactory sslSocketFactory = new SSLSocketFactory(createTrustAllSSLContext());

            Scheme httpScheme = new Scheme("http", 80, plainSocketFactory);
            Scheme httpsScheme = new Scheme("https", 443, sslSocketFactory);

            SchemeRegistry schemeRegistry = new SchemeRegistry();
            schemeRegistry.register(httpScheme);
            schemeRegistry.register(httpsScheme);

            ClientConnectionManager cm = new SingleClientConnManager(schemeRegistry);
            httpClient = new DefaultHttpClient(cm);
        } catch (Exception e) {
            httpClient = new DefaultHttpClient();
        }
    } else {
        httpClient = new DefaultHttpClient();
    }

    String httpProxyHost = EnvUtils.getEnv(HTTP_PROXY_HOST);
    String httpProxyPort = EnvUtils.getEnv(HTTP_PROXY_PORT);

    if ((httpProxyHost != null) && (httpProxyPort != null)) {
        HttpHost httpProxy = new HttpHost(httpProxyHost, Integer.parseInt(httpProxyPort));
        httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, httpProxy);
    }

    return httpClient;
}

From source file:ro.teodorbaciu.commons.client.ws.util.WebClientDevWrapper.java

/**
 * Provides a new instance of http client that wraps the 
 * instance specified as parameter.//from w w  w. j av  a  2s. co  m
 */
@SuppressWarnings("deprecation")
public static DefaultHttpClient wrapClient(HttpClient base) {
    try {
        SSLContext ctx = SSLContext.getInstance("TLS");
        X509TrustManager tm = new X509TrustManager() {

            @Override
            public void checkClientTrusted(X509Certificate[] arg0, String arg1)
                    throws java.security.cert.CertificateException {

            }

            @Override
            public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {

            }

            @Override
            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return null;
            }

        };
        X509HostnameVerifier verifier = new X509HostnameVerifier() {

            @Override
            public void verify(String string, SSLSocket ssls) throws IOException {
            }

            @Override
            public void verify(String string, X509Certificate xc) throws SSLException {
            }

            @Override
            public void verify(String string, String[] strings, String[] strings1) throws SSLException {
            }

            @Override
            public boolean verify(String string, SSLSession ssls) {
                return true;
            }
        };
        ctx.init(null, new TrustManager[] { tm }, null);
        SSLSocketFactory ssf = new SSLSocketFactory(ctx);
        ssf.setHostnameVerifier(verifier);
        ClientConnectionManager ccm = base.getConnectionManager();
        SchemeRegistry sr = ccm.getSchemeRegistry();
        sr.register(new Scheme("https", ssf, 443));
        return new DefaultHttpClient(ccm, base.getParams());
    } catch (Exception ex) {
        ex.printStackTrace();
        return null;
    }
}

From source file:com.cloudhopper.httpclient.util.HttpSender.java

static public Response postXml(String url, String username, String password, String requestXml)
        throws Exception {
    ///*from  www  .  j  a va 2 s. c o m*/
    // trust any SSL connection
    //
    TrustManager easyTrustManager = new X509TrustManager() {
        public void checkClientTrusted(java.security.cert.X509Certificate[] arg0, String arg1)
                throws CertificateException {
            // allow all
        }

        public void checkServerTrusted(java.security.cert.X509Certificate[] arg0, String arg1)
                throws CertificateException {
            // allow all
        }

        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return null;
        }
    };

    Scheme http = new Scheme("http", PlainSocketFactory.getSocketFactory(), 80);
    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 https = new Scheme("https", sf, 443);

    //SchemeRegistry sr = new SchemeRegistry();
    //sr.register(http);
    //sr.register(https);

    // create and initialize scheme registry
    //SchemeRegistry schemeRegistry = new SchemeRegistry();
    //schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));

    // create an HttpClient with the ThreadSafeClientConnManager.
    // This connection manager must be used if more than one thread will
    // be using the HttpClient.
    //ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(schemeRegistry);
    //cm.setMaxTotalConnections(1);

    DefaultHttpClient client = new DefaultHttpClient();

    client.getConnectionManager().getSchemeRegistry().register(https);

    HttpPost post = new HttpPost(url);

    StringEntity postEntity = new StringEntity(requestXml, "ISO-8859-1");
    postEntity.setContentType("text/xml; charset=\"ISO-8859-1\"");
    post.addHeader("SOAPAction", "\"\"");
    post.setEntity(postEntity);

    long start = System.currentTimeMillis();

    client.getCredentialsProvider().setCredentials(new AuthScope(null, AuthScope.ANY_PORT),
            new UsernamePasswordCredentials(username, password));

    BasicHttpContext localcontext = new BasicHttpContext();

    // Generate BASIC scheme object and stick it to the local
    // execution context
    BasicScheme basicAuth = new BasicScheme();
    localcontext.setAttribute("preemptive-auth", basicAuth);

    // Add as the first request interceptor
    client.addRequestInterceptor(new PreemptiveAuth(), 0);

    HttpResponse httpResponse = client.execute(post, localcontext);
    HttpEntity responseEntity = httpResponse.getEntity();

    Response rsp = new Response();

    // set the status line and reason
    rsp.statusCode = httpResponse.getStatusLine().getStatusCode();
    rsp.statusLine = httpResponse.getStatusLine().getReasonPhrase();

    // get an input stream
    rsp.body = EntityUtils.toString(responseEntity);

    // When HttpClient instance is no longer needed,
    // shut down the connection manager to ensure
    // immediate deallocation of all system resources
    client.getConnectionManager().shutdown();

    return rsp;
}

From source file:at.co.blogspot.javaskeleton.WebClientDevWrapper.java

public static HttpClient wrapClient(final HttpClient base, final int port) {
    try {/*from www.  j  a v a  2 s  .c  o m*/
        final SSLContext ctx = SSLContext.getInstance("TLS");
        final X509TrustManager tm = new X509TrustManager() {

            public void checkClientTrusted(final X509Certificate[] xcs, final String string)
                    throws CertificateException {
            }

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

            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }
        };
        final X509HostnameVerifier verifier = new X509HostnameVerifier() {

            @Override
            public void verify(final String string, final SSLSocket ssls) throws IOException {
            }

            @Override
            public void verify(final String string, final X509Certificate xc) throws SSLException {
            }

            @Override
            public void verify(final String string, final String[] strings, final String[] strings1)
                    throws SSLException {
            }

            @Override
            public boolean verify(final String string, final SSLSession ssls) {
                return true;
            }
        };
        ctx.init(null, new TrustManager[] { tm }, null);
        final SSLSocketFactory ssf = new SSLSocketFactory(ctx);
        ssf.setHostnameVerifier(verifier);
        final ClientConnectionManager ccm = base.getConnectionManager();
        final SchemeRegistry sr = ccm.getSchemeRegistry();
        sr.register(new Scheme("https", ssf, port));
        return new DefaultHttpClient(ccm, base.getParams());
    } catch (final Exception ex) {
        LOG.error("Error enabling https-connections", ex);
        return null;
    }
}

From source file:org.ttrssreader.net.deprecated.HttpClientFactory.java

/**
 * Create a socket factory with the custom key store
 *
 * @param keystorePassword the password to unlock the custom keystore
 * @return socket factory with custom key store
 *//*from w  w w  .jav a  2s .  c o  m*/
private static SSLSocketFactory newSslSocketFactory(String keystorePassword) {
    try {
        KeyStore keystore = SSLUtils.loadKeystore(keystorePassword);

        return new SSLSocketFactory(keystore);
    } catch (Exception e) {
        e.printStackTrace();
    }

    return null;
}

From source file:gr.wavesoft.webng.io.web.WebStreams.java

public static void Initialize() {

    schemeRegistry = new SchemeRegistry();

    // Register HTTP
    schemeRegistry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory()));

    // Register HTTPS with WebNG Extensions
    try {/*from   w ww . j a  v  a 2 s . c om*/
        schemeRegistry.register(new Scheme("https", 443, new SSLSocketFactory(WebNGKeyStore.getKeyStore())));

    } catch (NoSuchAlgorithmException ex) {
        systemLogger.except(ex);
    } catch (KeyManagementException ex) {
        systemLogger.except(ex);
    } catch (KeyStoreException ex) {
        systemLogger.except(ex);
    } catch (UnrecoverableKeyException ex) {
        systemLogger.except(ex);
    }

    // Setup connection manager
    connectionManager = new PoolingClientConnectionManager(schemeRegistry);

    // Increase max total connection to 200
    connectionManager.setMaxTotal(200);

    // Increase default max connection per route to 20
    connectionManager.setDefaultMaxPerRoute(20);

    // Increase max connections for localhost:80 to 50
    HttpHost localhost = new HttpHost("locahost", 80);
    connectionManager.setMaxPerRoute(new HttpRoute(localhost), 50);

    // Setup http client
    httpClient = new DefaultHttpClient(connectionManager);

    // Setup cookie cache
    //((DefaultHttpClient)httpClient).setCookieStore(WebNGCache.instanceCookieCache());

    // Setup cache
    CacheConfig cacheConfig = new CacheConfig();
    cacheConfig.setMaxCacheEntries(WebNGCache.config.MAX_ENTRIES_MEM);
    cacheConfig.setMaxObjectSize(WebNGCache.config.MAX_OBJECT_SIZE);

    cachingClient = new CachingHttpClient(httpClient, WebNGCache.instanceDiskCacheStorage(), cacheConfig);

}

From source file:eu.musesproject.client.connectionmanager.TLSManager.java

/**
 * Create SSLFactory object using certificate saved in the device
 * @return SSLSocketFactory//w w  w  . ja  v  a  2  s.c o  m
 */

private SSLSocketFactory newSslSocketFactory() {
    try {
        InputStream in = new ByteArrayInputStream(MusesUtils.getCertificate().getBytes());
        KeyStore trustedStore = null;

        if (in != null) {
            trustedStore = convertCerToBKS(in, "muses alias", "muses11".toCharArray());
        }
        SSLSocketFactory sf = new SSLSocketFactory(trustedStore);
        sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        return sf;
    } catch (Exception e) {
        throw new AssertionError(e);
    }
}

From source file:neembuu.release1.httpclient.NHttpClient.java

public static DefaultHttpClient getNewInstance() {
    DefaultHttpClient new_httpClient = null;
    new_httpClient = new DefaultHttpClient();
    GlobalTestSettings.ProxySettings proxySettings = GlobalTestSettings.getGlobalProxySettings();
    HttpContext context = new BasicHttpContext();
    SchemeRegistry schemeRegistry = new SchemeRegistry();

    schemeRegistry.register(new Scheme("http", new PlainSocketFactory(), 80));

    try {/*from w w w.  ja v  a  2  s  .c  o m*/
        KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        schemeRegistry.register(new Scheme("https", new SSLSocketFactory(keyStore), 8080));
    } catch (Exception a) {
        a.printStackTrace(System.err);
    }

    context.setAttribute(ClientContext.SCHEME_REGISTRY, schemeRegistry);
    context.setAttribute(ClientContext.AUTHSCHEME_REGISTRY,
            new BasicScheme()/*file.httpClient.getAuthSchemes()*/);

    context.setAttribute(ClientContext.COOKIESPEC_REGISTRY,
            new_httpClient.getCookieSpecs()/*file.httpClient.getCookieSpecs()*/
    );

    BasicCookieStore basicCookieStore = new BasicCookieStore();

    context.setAttribute(ClientContext.COOKIE_STORE, basicCookieStore/*file.httpClient.getCookieStore()*/);
    context.setAttribute(ClientContext.CREDS_PROVIDER,
            new BasicCredentialsProvider()/*file.httpClient.getCredentialsProvider()*/);

    HttpConnection hc = new DefaultHttpClientConnection();
    context.setAttribute(ExecutionContext.HTTP_CONNECTION, hc);

    //System.out.println(file.httpClient.getParams().getParameter("http.useragent"));
    HttpParams httpParams = new BasicHttpParams();

    if (proxySettings != null) {
        AuthState as = new AuthState();
        as.setCredentials(new UsernamePasswordCredentials(proxySettings.userName, proxySettings.password));
        as.setAuthScope(AuthScope.ANY);
        as.setAuthScheme(new BasicScheme());
        httpParams.setParameter(ClientContext.PROXY_AUTH_STATE, as);
        httpParams.setParameter("http.proxy_host", new HttpHost(proxySettings.host, proxySettings.port));
    }

    new_httpClient = new DefaultHttpClient(
            new SingleClientConnManager(httpParams/*file.httpClient.getParams()*/, schemeRegistry),
            httpParams/*file.httpClient.getParams()*/);

    if (proxySettings != null) {
        new_httpClient.getCredentialsProvider().setCredentials(AuthScope.ANY,
                new UsernamePasswordCredentials(proxySettings.userName, proxySettings.password));
    }

    return new_httpClient;
}