Example usage for org.apache.http.impl.conn PoolingClientConnectionManager PoolingClientConnectionManager

List of usage examples for org.apache.http.impl.conn PoolingClientConnectionManager PoolingClientConnectionManager

Introduction

In this page you can find the example usage for org.apache.http.impl.conn PoolingClientConnectionManager PoolingClientConnectionManager.

Prototype

public PoolingClientConnectionManager(final SchemeRegistry schreg) 

Source Link

Usage

From source file:org.opcfoundation.ua.transport.https.HttpsClient.java

/**
 * Initialize HttpsClient. //from  w  w w.ja v a  2s.  co  m
 * 
 * @param connectUrl
 * @param tcs
 */
public void initialize(String connectUrl, TransportChannelSettings tcs, EncoderContext ctx)
        throws ServiceResultException {

    this.connectUrl = connectUrl;
    this.securityPolicyUri = tcs.getDescription().getSecurityPolicyUri();
    this.transportChannelSettings = tcs;
    HttpsSettings httpsSettings = tcs.getHttpsSettings();
    HttpsSecurityPolicy[] policies = httpsSettings.getHttpsSecurityPolicies();
    if (policies != null && policies.length > 0)
        securityPolicy = policies[policies.length - 1];
    else
        securityPolicy = HttpsSecurityPolicy.TLS_1_1;
    // securityPolicy = SecurityPolicy.getSecurityPolicy( this.securityPolicyUri );
    if (securityPolicy != HttpsSecurityPolicy.TLS_1_0 && securityPolicy != HttpsSecurityPolicy.TLS_1_1
            && securityPolicy != HttpsSecurityPolicy.TLS_1_2)
        throw new ServiceResultException(StatusCodes.Bad_SecurityChecksFailed,
                "Https Client doesn't support securityPolicy " + securityPolicy);
    if (logger.isDebugEnabled()) {
        logger.debug("initialize: url={}; settings={}", tcs.getDescription().getEndpointUrl(),
                ObjectUtils.printFields(tcs));
    }

    // Setup Encoder
    EndpointConfiguration endpointConfiguration = tcs.getConfiguration();
    encoderCtx = ctx;
    encoderCtx.setMaxArrayLength(
            endpointConfiguration.getMaxArrayLength() != null ? endpointConfiguration.getMaxArrayLength() : 0);
    encoderCtx.setMaxStringLength(
            endpointConfiguration.getMaxStringLength() != null ? endpointConfiguration.getMaxStringLength()
                    : 0);
    encoderCtx.setMaxByteStringLength(endpointConfiguration.getMaxByteStringLength() != null
            ? endpointConfiguration.getMaxByteStringLength()
            : 0);
    encoderCtx.setMaxMessageSize(
            endpointConfiguration.getMaxMessageSize() != null ? endpointConfiguration.getMaxMessageSize() : 0);

    timer = TimerUtil.getTimer();
    try {
        SchemeRegistry sr = new SchemeRegistry();
        if (protocol.equals(UriUtil.SCHEME_HTTPS)) {
            SSLContext sslcontext = SSLContext.getInstance("TLS");
            sslcontext.init(httpsSettings.getKeyManagers(), httpsSettings.getTrustManagers(), null);
            X509HostnameVerifier hostnameVerifier = httpsSettings.getHostnameVerifier() != null
                    ? httpsSettings.getHostnameVerifier()
                    : SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;
            SSLSocketFactory sf = new SSLSocketFactory(sslcontext, hostnameVerifier) {
                protected void prepareSocket(javax.net.ssl.SSLSocket socket) throws IOException {
                    socket.setEnabledCipherSuites(cipherSuites);
                };
            };

            SSLEngine sslEngine = sslcontext.createSSLEngine();
            String[] enabledCipherSuites = sslEngine.getEnabledCipherSuites();
            cipherSuites = CryptoUtil.filterCipherSuiteList(enabledCipherSuites,
                    securityPolicy.getCipherSuites());

            logger.info("Enabled protocols in SSL Engine are {}",
                    Arrays.toString(sslEngine.getEnabledProtocols()));
            logger.info("Enabled CipherSuites in SSL Engine are {}", Arrays.toString(enabledCipherSuites));
            logger.info("Client CipherSuite selection for {} is {}", securityPolicy.getPolicyUri(),
                    Arrays.toString(cipherSuites));

            Scheme https = new Scheme("https", 443, sf);
            sr.register(https);
        }

        if (protocol.equals(UriUtil.SCHEME_HTTP)) {
            Scheme http = new Scheme("http", 80, PlainSocketFactory.getSocketFactory());
            sr.register(http);
        }

        if (ccm == null) {
            PoolingClientConnectionManager pccm = new PoolingClientConnectionManager(sr);
            ccm = pccm;
            pccm.setMaxTotal(maxConnections);
            pccm.setDefaultMaxPerRoute(maxConnections);
        }
        BasicHttpParams httpParams = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(httpParams,
                transportChannelSettings.getConfiguration().getOperationTimeout());
        HttpConnectionParams.setSoTimeout(httpParams, 0);
        httpclient = new DefaultHttpClient(ccm, httpParams);

        // Set username and password authentication
        if (httpsSettings.getUsername() != null && httpsSettings.getPassword() != null) {
            BasicCredentialsProvider credsProvider = new BasicCredentialsProvider();
            credsProvider.setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),
                    new UsernamePasswordCredentials(httpsSettings.getUsername(), httpsSettings.getPassword()));
            httpclient.setCredentialsProvider(credsProvider);
        }

    } catch (NoSuchAlgorithmException e) {
        new ServiceResultException(e);
    } catch (KeyManagementException e) {
        new ServiceResultException(e);
    }

}

From source file:org.switchyard.component.resteasy.util.ClientInvoker.java

/**
 * Create a RESTEasy invoker client.//from  w w w  .  j ava 2  s.co  m
 *
 * @param basePath The base path for the class
 * @param resourceClass The JAX-RS Resource Class
 * @param method The JAX-RS Resource Class's method
 * @param model Configuration model
 */
public ClientInvoker(String basePath, Class<?> resourceClass, Method method, RESTEasyBindingModel model) {
    Set<String> httpMethods = IsHttpMethod.getHttpMethods(method);
    _baseUri = createUri(basePath);
    if ((httpMethods == null || httpMethods.size() == 0) && method.isAnnotationPresent(Path.class)
            && method.getReturnType().isInterface()) {
        _subResourcePath = createSubResourcePath(basePath, method);
    } else if (httpMethods == null || httpMethods.size() != 1) {
        throw RestEasyMessages.MESSAGES
                .youMustUseAtLeastOneButNoMoreThanOneHttpMethodAnnotationOn(method.toString());
    }
    _httpMethod = httpMethods.iterator().next();
    _resourceClass = resourceClass;
    _method = method;
    try {
        _uri = (UriBuilder) URIBUILDER_CLASS.newInstance();
    } catch (InstantiationException ie) {
        throw new RuntimeException(ie);
    } catch (IllegalAccessException iae) {
        throw new RuntimeException(iae);
    }
    _uri.uri(_baseUri);
    if (_resourceClass.isAnnotationPresent(Path.class)) {
        _uri.path(_resourceClass);
    }
    if (_method.isAnnotationPresent(Path.class)) {
        _uri.path(_method);
    }

    _providerFactory = new ResteasyProviderFactory();

    boolean useBuiltins = true; // use builtin @Provider classes by default
    if (model.getContextParamsConfig() != null) {
        Map<String, String> contextParams = model.getContextParamsConfig().toMap();

        // Set use builtin @Provider classes
        String registerBuiltins = contextParams.get(ResteasyContextParameters.RESTEASY_USE_BUILTIN_PROVIDERS);
        if (registerBuiltins != null) {
            useBuiltins = Boolean.parseBoolean(registerBuiltins);
        }

        // Register @Provider classes
        List<Class<?>> providerClasses = RESTEasyUtil.getProviderClasses(contextParams);
        if (providerClasses != null) {
            for (Class<?> pc : providerClasses) {
                _providerFactory.registerProvider(pc);
            }
        }

        List<ClientErrorInterceptor> interceptors = RESTEasyUtil.getClientErrorInterceptors(contextParams);
        if (interceptors != null) {
            for (ClientErrorInterceptor interceptor : interceptors) {
                _providerFactory.addClientErrorInterceptor(interceptor);
            }
        }
    }
    if (useBuiltins) {
        _providerFactory.setRegisterBuiltins(true);
        RegisterBuiltin.register(_providerFactory);
    }

    _extractorFactory = new DefaultEntityExtractorFactory();
    _extractor = _extractorFactory.createExtractor(_method);
    _marshallers = ClientMarshallerFactory.createMarshallers(_resourceClass, _method, _providerFactory, null);
    _accepts = MediaTypeHelper.getProduces(_resourceClass, method, null);
    ClientInvokerInterceptorFactory.applyDefaultInterceptors(this, _providerFactory, _resourceClass, _method);

    // Client executor
    SchemeRegistry schemeRegistry = new SchemeRegistry();
    int port = _baseUri.getPort();
    if (_baseUri.getScheme().startsWith("https")) {
        if (port == -1) {
            port = 443;
        }
        SSLSocketFactory sslFactory = getSSLSocketFactory(model.getSSLContextConfig());
        if (sslFactory == null) {
            sslFactory = SSLSocketFactory.getSocketFactory();
        }
        schemeRegistry.register(new Scheme(_baseUri.getScheme(), port, sslFactory));
    } else {
        if (port == -1) {
            port = 80;
        }
        schemeRegistry.register(new Scheme(_baseUri.getScheme(), port, PlainSocketFactory.getSocketFactory()));
    }
    PoolingClientConnectionManager cm = new PoolingClientConnectionManager(schemeRegistry);
    cm.setMaxTotal(200);
    cm.setDefaultMaxPerRoute(20);
    HttpClient httpClient = new DefaultHttpClient(cm);
    _executor = new ApacheHttpClient4Executor(httpClient);
    // register ApacheHttpClient4ExceptionMapper manually for local instance of ResteasyProviderFactory
    Type exceptionType = Types.getActualTypeArgumentsOfAnInterface(ApacheHttpClient4ExceptionMapper.class,
            ClientExceptionMapper.class)[0];
    _providerFactory.addClientExceptionMapper(new ApacheHttpClient4ExceptionMapper(), exceptionType);

    // Authentication settings
    if (model.hasAuthentication()) {
        // Set authentication
        AuthScope authScope = null;
        Credentials credentials = null;
        if (model.isBasicAuth()) {
            authScope = createAuthScope(model.getBasicAuthConfig().getHost(),
                    model.getBasicAuthConfig().getPort(), model.getBasicAuthConfig().getRealm());
            credentials = new UsernamePasswordCredentials(model.getBasicAuthConfig().getUser(),
                    model.getBasicAuthConfig().getPassword());
            // Create AuthCache instance
            AuthCache authCache = new BasicAuthCache();
            authCache.put(new HttpHost(authScope.getHost(), authScope.getPort()),
                    new BasicScheme(ChallengeState.TARGET));
            BasicHttpContext context = new BasicHttpContext();
            context.setAttribute(ClientContext.AUTH_CACHE, authCache);
            ((ApacheHttpClient4Executor) _executor).setHttpContext(context);
        } else {
            authScope = createAuthScope(model.getNtlmAuthConfig().getHost(),
                    model.getNtlmAuthConfig().getPort(), model.getNtlmAuthConfig().getRealm());
            credentials = new NTCredentials(model.getNtlmAuthConfig().getUser(),
                    model.getNtlmAuthConfig().getPassword(), "", model.getNtlmAuthConfig().getDomain());
        }
        ((DefaultHttpClient) httpClient).getCredentialsProvider().setCredentials(authScope, credentials);
    } else {
        ProxyModel proxy = model.getProxyConfig();
        if (proxy != null) {
            HttpHost proxyHost = null;
            if (proxy.getPort() != null) {
                proxyHost = new HttpHost(proxy.getHost(), Integer.valueOf(proxy.getPort()).intValue());
            } else {
                proxyHost = new HttpHost(proxy.getHost(), -1);
            }
            if (proxy.getUser() != null) {
                AuthScope authScope = new AuthScope(proxy.getHost(),
                        Integer.valueOf(proxy.getPort()).intValue(), AuthScope.ANY_REALM);
                Credentials credentials = new UsernamePasswordCredentials(proxy.getUser(), proxy.getPassword());
                AuthCache authCache = new BasicAuthCache();
                authCache.put(proxyHost, new BasicScheme(ChallengeState.PROXY));
                ((DefaultHttpClient) httpClient).getCredentialsProvider().setCredentials(authScope,
                        credentials);
                BasicHttpContext context = new BasicHttpContext();
                context.setAttribute(ClientContext.AUTH_CACHE, authCache);
                ((ApacheHttpClient4Executor) _executor).setHttpContext(context);
            }
            httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxyHost);
        }
    }
    Integer timeout = model.getTimeout();
    if (timeout != null) {
        HttpParams httpParams = httpClient.getParams();
        HttpConnectionParams.setConnectionTimeout(httpParams, timeout);
        HttpConnectionParams.setSoTimeout(httpParams, timeout);
    }
}

From source file:com.da.daum.DaumCafeBungImgList.java

private HttpClient getPoolHttpClient() {
    HttpClient httpclient;//  w  ww .  ja  v a  2 s .  c o  m
    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory()));
    schemeRegistry.register(new Scheme("https", 443, SSLSocketFactory.getSocketFactory()));
    PoolingClientConnectionManager cm = new PoolingClientConnectionManager(schemeRegistry);
    // Increase max total connection to 200
    cm.setMaxTotal(200);
    // Increase default max connection per route to 20
    cm.setDefaultMaxPerRoute(20);
    // Increase max connections for localhost:80 to 50
    HttpHost localhost = new HttpHost("locahost", 80);
    cm.setMaxPerRoute(new HttpRoute(localhost), 50);
    //DefaultHttpClient httpclient = new DefaultHttpClient();
    httpclient = new DefaultHttpClient(cm);
    return httpclient;
}

From source file:org.apache.marmotta.platform.core.services.http.HttpClientServiceImpl.java

@PostConstruct
protected void initialize() {
    try {/*from w  w  w  .  ja  va 2  s  .  co m*/
        lock.writeLock().lock();

        httpParams = new BasicHttpParams();
        String userAgentString = "Apache Marmotta/"
                + configurationService.getStringConfiguration("kiwi.version") + " (running at "
                + configurationService.getServerUri() + ")" + " lmf-core/"
                + configurationService.getStringConfiguration("kiwi.version");
        userAgentString = configurationService.getStringConfiguration("core.http.user_agent", userAgentString);

        httpParams.setIntParameter(CoreConnectionPNames.SO_TIMEOUT,
                configurationService.getIntConfiguration("core.http.so_timeout", 60000));
        httpParams.setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT,
                configurationService.getIntConfiguration("core.http.connection_timeout", 10000));

        httpParams.setBooleanParameter(ClientPNames.HANDLE_REDIRECTS, true);
        httpParams.setIntParameter(ClientPNames.MAX_REDIRECTS, 3);

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

        PoolingClientConnectionManager cm = new PoolingClientConnectionManager(schemeRegistry);
        cm.setMaxTotal(configurationService.getIntConfiguration(CoreOptions.HTTP_MAX_CONNECTIONS, 20));
        cm.setDefaultMaxPerRoute(
                configurationService.getIntConfiguration(CoreOptions.HTTP_MAX_CONNECTIONS_PER_ROUTE, 10));

        final DefaultHttpClient hc = new DefaultHttpClient(cm, httpParams);
        hc.setRedirectStrategy(new LMFRedirectStrategy());
        hc.setHttpRequestRetryHandler(new LMFHttpRequestRetryHandler());
        hc.removeRequestInterceptorByClass(org.apache.http.protocol.RequestUserAgent.class);
        hc.addRequestInterceptor(new LMFRequestUserAgent(userAgentString));

        if (configurationService.getBooleanConfiguration(CoreOptions.HTTP_CLIENT_CACHE_ENABLE, true)) {
            CacheConfig cacheConfig = new CacheConfig();
            // FIXME: Hardcoded constants - is this useful?
            cacheConfig.setMaxCacheEntries(1000);
            cacheConfig.setMaxObjectSize(81920);

            final HttpCacheStorage cacheStore = new MapHttpCacheStorage(httpCache);

            this.httpClient = new MonitoredHttpClient(new CachingHttpClient(hc, cacheStore, cacheConfig));
        } else {
            this.httpClient = new MonitoredHttpClient(hc);
        }
        bytesSent.set(0);
        bytesReceived.set(0);
        requestsExecuted.set(0);

        idleConnectionMonitorThread = new IdleConnectionMonitorThread(httpClient.getConnectionManager());
        idleConnectionMonitorThread.start();

        StatisticsProvider stats = new StatisticsProvider(cm);
        statisticsService.registerModule(HttpClientService.class.getSimpleName(), stats);
    } finally {
        lock.writeLock().unlock();
    }
}

From source file:org.hupo.psi.mi.psicquic.ws.legacy.SolrBasedPsicquicRestService10.java

private HttpClient createHttpClient() {
    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory()));
    schemeRegistry.register(new Scheme("https", 443, SSLSocketFactory.getSocketFactory()));

    PoolingClientConnectionManager cm = new PoolingClientConnectionManager(schemeRegistry);
    cm.setMaxTotal(SolrBasedPsicquicService.maxTotalConnections);
    cm.setDefaultMaxPerRoute(SolrBasedPsicquicService.defaultMaxConnectionsPerHost);

    HttpClient httpClient = new DefaultHttpClient(cm);

    String proxyHost = config.getProxyHost();
    String proxyPort = config.getProxyPort();

    if (isValueSet(proxyHost) && proxyHost.trim().length() > 0 && isValueSet(proxyPort)
            && proxyPort.trim().length() > 0) {
        try {//  w w w.  ja va 2 s . c  o  m
            HttpHost proxy = new HttpHost(proxyHost, Integer.parseInt(proxyPort));
            httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
        } catch (Exception e) {
            logger.error("Impossible to create proxy host:" + proxyHost + ", port:" + proxyPort, e);
        }
    }

    return httpClient;
}

From source file:org.lightcouch.CouchDbClientBase.java

/**
 * @return {@link DefaultHttpClient} instance.
 */// w w  w  .  ja  v  a2s .  com
private HttpClient createHttpClient(CouchDbProperties props) {
    DefaultHttpClient httpclient = null;
    try {
        SchemeSocketFactory ssf = null;
        if (props.getProtocol().equals("https")) {
            TrustManager trustManager = new X509TrustManager() {
                public void checkClientTrusted(X509Certificate[] chain, String authType)
                        throws CertificateException {
                }

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

                public X509Certificate[] getAcceptedIssuers() {
                    return null;
                }
            };
            SSLContext sslcontext = SSLContext.getInstance("TLS");
            sslcontext.init(null, new TrustManager[] { trustManager }, null);
            ssf = new SSLSocketFactory(sslcontext, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
            SSLSocket socket = (SSLSocket) ssf.createSocket(null);
            socket.setEnabledCipherSuites(new String[] { "SSL_RSA_WITH_RC4_128_MD5" });
        } else {
            ssf = PlainSocketFactory.getSocketFactory();
        }
        SchemeRegistry schemeRegistry = new SchemeRegistry();
        schemeRegistry.register(new Scheme(props.getProtocol(), props.getPort(), ssf));
        PoolingClientConnectionManager ccm = new PoolingClientConnectionManager(schemeRegistry);
        httpclient = new DefaultHttpClient(ccm);
        host = new HttpHost(props.getHost(), props.getPort(), props.getProtocol());
        context = new BasicHttpContext();
        // Http params
        httpclient.getParams().setParameter(CoreProtocolPNames.HTTP_CONTENT_CHARSET, "UTF-8");
        httpclient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, props.getSocketTimeout());
        httpclient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT,
                props.getConnectionTimeout());
        int maxConnections = props.getMaxConnections();
        if (maxConnections != 0) {
            ccm.setMaxTotal(maxConnections);
            ccm.setDefaultMaxPerRoute(maxConnections);
        }
        if (props.getProxyHost() != null) {
            HttpHost proxy = new HttpHost(props.getProxyHost(), props.getProxyPort());
            httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
        }
        // basic authentication
        if (props.getUsername() != null && props.getPassword() != null) {
            httpclient.getCredentialsProvider().setCredentials(new AuthScope(props.getHost(), props.getPort()),
                    new UsernamePasswordCredentials(props.getUsername(), props.getPassword()));
            props.clearPassword();
            AuthCache authCache = new BasicAuthCache();
            BasicScheme basicAuth = new BasicScheme();
            authCache.put(host, basicAuth);
            context.setAttribute(ClientContext.AUTH_CACHE, authCache);
        }
        // request interceptor
        httpclient.addRequestInterceptor(new HttpRequestInterceptor() {
            public void process(final HttpRequest request, final HttpContext context) throws IOException {
                if (log.isInfoEnabled())
                    log.info(">> " + request.getRequestLine());
            }
        });
        // response interceptor
        httpclient.addResponseInterceptor(new HttpResponseInterceptor() {
            public void process(final HttpResponse response, final HttpContext context) throws IOException {
                validate(response);
                if (log.isInfoEnabled())
                    log.info("<< Status: " + response.getStatusLine().getStatusCode());
            }
        });
    } catch (Exception e) {
        log.error("Error Creating HTTP client. " + e.getMessage());
        throw new IllegalStateException(e);
    }
    return httpclient;
}

From source file:com.ah.be.common.PresenceUtil.java

public static HttpClient getHttpClientInstance(int maxConnections) {
    try {//from  w ww .  java2s .c om
        SSLContext ctx = SSLContext.getInstance("TLS");
        ctx.init(null, new TrustManager[] { new ClientTrustManager() }, null);
        SSLSocketFactory ssf = new SSLSocketFactory(ctx, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        SchemeRegistry schemeRegistry = new SchemeRegistry();
        schemeRegistry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory()));
        schemeRegistry.register(new Scheme("https", 443, ssf));
        PoolingClientConnectionManager connMgr = new PoolingClientConnectionManager(schemeRegistry);
        connMgr.setMaxTotal(maxConnections);
        connMgr.setDefaultMaxPerRoute(maxConnections);

        HttpParams params = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(params, SOCKET_TIMEOUT);
        HttpConnectionParams.setSoTimeout(params, SOCKET_TIMEOUT);
        HttpClient httpClient = new DefaultHttpClient(connMgr, params);
        return httpClient;
    } catch (Exception e) {
        log.error("getHttpClientInstance error.", e);
        return null;
    }
}

From source file:fr.eolya.utils.http.HttpLoader.java

/**
 * @param /*  w  w w .  j av a2  s . c o m*/
 * @return
 */
private HttpClient getHttpClient(String url) {
    try {
        // ClientConnectionManager
        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));

        ClientConnectionManager ccm = new PoolingClientConnectionManager(registry);

        // Params
        HttpParams httpParams = getHttpParams();

        // DefaultHttpClient
        DefaultHttpClient httpClient = new DefaultHttpClient(ccm, httpParams);

        // Proxy
        setProxy(httpClient, url, proxyHost, proxyPort, proxyExclude, proxyUserName, proxyPassword);

        //         if (StringUtils.isNotEmpty(proxyHost)) {
        //            if (StringUtils.isNotEmpty(proxyUserName) && StringUtils.isNotEmpty(proxyPassword)) {
        //               httpClient.getCredentialsProvider().setCredentials(
        //                      new AuthScope(proxyHost,Integer.valueOf(proxyPort)),
        //                      new UsernamePasswordCredentials(proxyUserName, proxyPassword));
        //            }
        //            HttpHost proxy = new HttpHost(proxyHost,Integer.valueOf(proxyPort));
        //            httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY,proxy);
        //         } else {
        //            httpClient.getParams().removeParameter(ConnRoutePNames.DEFAULT_PROXY);
        //         }

        // Cookies
        if (cookies != null) {
            CookieStore cookieStore = new BasicCookieStore();
            Iterator<Entry<String, String>> it = cookies.entrySet().iterator();
            while (it.hasNext()) {
                Map.Entry<String, String> pairs = (Map.Entry<String, String>) it.next();
                BasicClientCookie cookie = new BasicClientCookie(pairs.getKey(), pairs.getValue());
                //cookie.setDomain("your domain");
                cookie.setPath("/");
                cookieStore.addCookie(cookie);
            }
            httpClient.setCookieStore(cookieStore);
        }

        return new DecompressingHttpClient(httpClient);
    } catch (Exception e) {
        return new DecompressingHttpClient(new DefaultHttpClient());
    }
}

From source file:org.string_db.psicquic.ws.StringdbSolrBasedPsicquicRestService.java

protected HttpClient createHttpClient() {
    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory()));
    schemeRegistry.register(new Scheme("https", 443, SSLSocketFactory.getSocketFactory()));

    PoolingClientConnectionManager cm = new PoolingClientConnectionManager(schemeRegistry);
    cm.setMaxTotal(maxTotalConnections);
    cm.setDefaultMaxPerRoute(defaultMaxConnectionsPerHost);

    HttpClient httpClient = new DefaultHttpClient(cm);

    String proxyHost = config.getProxyHost();
    String proxyPort = config.getProxyPort();

    if (isValueSet(proxyHost) && proxyHost.trim().length() > 0 && isValueSet(proxyPort)
            && proxyPort.trim().length() > 0) {
        try {/*from   ww  w. j  av a2  s  . co  m*/
            HttpHost proxy = new HttpHost(proxyHost, Integer.parseInt(proxyPort));
            httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
        } catch (Exception e) {
            logger.error("Impossible to create proxy host:" + proxyHost + ", port:" + proxyPort, e);
        }
    }

    return httpClient;
}

From source file:org.apache.axis2.transport.http.impl.httpclient4.HTTPSenderImpl.java

protected AbstractHttpClient getHttpClient(MessageContext msgContext) {
    ConfigurationContext configContext = msgContext.getConfigurationContext();

    AbstractHttpClient httpClient = (AbstractHttpClient) msgContext
            .getProperty(HTTPConstants.CACHED_HTTP_CLIENT);

    if (httpClient == null) {
        httpClient = (AbstractHttpClient) configContext.getProperty(HTTPConstants.CACHED_HTTP_CLIENT);
    }/*from   w  w  w . j  a v  a  2 s  . com*/

    if (httpClient != null) {
        return httpClient;
    }

    synchronized (this) {
        httpClient = (AbstractHttpClient) msgContext.getProperty(HTTPConstants.CACHED_HTTP_CLIENT);

        if (httpClient == null) {
            httpClient = (AbstractHttpClient) configContext.getProperty(HTTPConstants.CACHED_HTTP_CLIENT);
        }

        if (httpClient != null) {
            return httpClient;
        }

        ClientConnectionManager connManager = (ClientConnectionManager) msgContext
                .getProperty(HTTPConstants.MULTITHREAD_HTTP_CONNECTION_MANAGER);
        if (connManager == null) {
            connManager = (ClientConnectionManager) msgContext
                    .getProperty(HTTPConstants.MULTITHREAD_HTTP_CONNECTION_MANAGER);
        }
        if (connManager == null) {
            // reuse HttpConnectionManager
            synchronized (configContext) {
                connManager = (ClientConnectionManager) configContext
                        .getProperty(HTTPConstants.MULTITHREAD_HTTP_CONNECTION_MANAGER);
                if (connManager == null) {
                    log.trace("Making new ConnectionManager");
                    SchemeRegistry schemeRegistry = new SchemeRegistry();
                    schemeRegistry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory()));
                    schemeRegistry.register(new Scheme("https", 443, SSLSocketFactory.getSocketFactory()));

                    connManager = new PoolingClientConnectionManager(schemeRegistry);
                    ((PoolingClientConnectionManager) connManager).setMaxTotal(200);
                    ((PoolingClientConnectionManager) connManager).setDefaultMaxPerRoute(200);
                    configContext.setProperty(HTTPConstants.MULTITHREAD_HTTP_CONNECTION_MANAGER, connManager);
                }
            }
        }
        /*
         * Create a new instance of HttpClient since the way it is used here
         * it's not fully thread-safe.
         */
        HttpParams clientParams = new BasicHttpParams();
        clientParams.setParameter(CoreProtocolPNames.HTTP_ELEMENT_CHARSET, "UTF-8");
        httpClient = new DefaultHttpClient(connManager, clientParams);

        //We don't need to set timeout for connection manager, since we are doing it below
        // and its enough

        // Get the timeout values set in the runtime
        initializeTimeouts(msgContext, httpClient);

        return httpClient;
    }
}