Example usage for org.apache.http.impl.client DefaultHttpClient getParams

List of usage examples for org.apache.http.impl.client DefaultHttpClient getParams

Introduction

In this page you can find the example usage for org.apache.http.impl.client DefaultHttpClient getParams.

Prototype

public synchronized final HttpParams getParams() 

Source Link

Usage

From source file:org.cloudifysource.restclient.RestClient.java

private RestClientExecutor createExecutor(final URL url, final String apiVersion) throws RestClientException {
    DefaultHttpClient httpClient;
    if (HTTPS.equals(url.getProtocol())) {
        httpClient = getSSLHttpClient(url);
    } else {// w  ww. ja v  a  2  s.c o m
        httpClient = new DefaultHttpClient();
    }
    final HttpParams httpParams = httpClient.getParams();
    HttpConnectionParams.setConnectionTimeout(httpParams, CloudifyConstants.DEFAULT_HTTP_CONNECTION_TIMEOUT);
    HttpConnectionParams.setSoTimeout(httpParams, CloudifyConstants.DEFAULT_HTTP_READ_TIMEOUT);
    return new RestClientExecutor(httpClient, url);
}

From source file:org.eobjects.datacleaner.user.UserPreferencesImpl.java

@Override
public HttpClient createHttpClient() {
    final ClientConnectionManager connectionManager = new PoolingClientConnectionManager();
    final DefaultHttpClient httpClient = new DefaultHttpClient(connectionManager);

    if (isProxyEnabled()) {
        // set up HTTP proxy
        final String proxyHostname = getProxyHostname();
        final int proxyPort = getProxyPort();

        try {/*  ww w .j a v  a2s.  c  o  m*/
            final HttpHost proxy = new HttpHost(proxyHostname, proxyPort);
            httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);

            if (isProxyAuthenticationEnabled()) {
                final AuthScope authScope = new AuthScope(proxyHostname, proxyPort);
                final String proxyUsername = getProxyUsername();
                final UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(proxyUsername,
                        getProxyPassword());
                httpClient.getCredentialsProvider().setCredentials(authScope, credentials);

                final int backslashIndex = proxyUsername.lastIndexOf('\\');
                final String ntUsername;
                final String ntDomain;
                if (backslashIndex != -1) {
                    ntUsername = proxyUsername.substring(backslashIndex + 1);
                    ntDomain = proxyUsername.substring(0, backslashIndex);
                } else {
                    ntUsername = proxyUsername;
                    ntDomain = System.getProperty("datacleaner.proxy.domain");
                }

                String workstation = System.getProperty("datacleaner.proxy.workstation");
                if (Strings.isNullOrEmpty(workstation)) {
                    String computername = InetAddress.getLocalHost().getHostName();
                    workstation = computername;
                }

                NTCredentials ntCredentials = new NTCredentials(ntUsername, getProxyPassword(), workstation,
                        ntDomain);
                AuthScope ntAuthScope = new AuthScope(proxyHostname, proxyPort, AuthScope.ANY_REALM, "ntlm");
                httpClient.getCredentialsProvider().setCredentials(ntAuthScope, ntCredentials);
            }
        } catch (Exception e) {
            // ignore proxy creation and return http client without it
            logger.error("Unexpected error occurred while initializing HTTP proxy", e);
        }
    }

    return httpClient;
}

From source file:org.mule.modules.quickbooks.api.AbstractQuickBooksClientOAuth.java

public static DefaultHttpClient getThreadSafeClient() {
    DefaultHttpClient client = new DefaultHttpClient();
    ClientConnectionManager mgr = client.getConnectionManager();
    HttpParams params = client.getParams();

    client = new DefaultHttpClient(new ThreadSafeClientConnManager(params, mgr.getSchemeRegistry()), params);
    client.setHttpRequestRetryHandler(new HttpRequestRetryHandler() {
        @Override//from w  w w  .  jav a 2 s .  c  o  m
        public boolean retryRequest(IOException exception, int executionCount, HttpContext context) {
            if (executionCount > 3) {
                LOGGER.warn("Maximum tries reached for client http pool ");
                return false;
            }
            if (exception instanceof org.apache.http.NoHttpResponseException) {
                LOGGER.warn("No response from server on " + executionCount + " call");
                return true;
            }
            return false;
        }
    });

    return client;
}

From source file:org.rhq.maven.plugins.UploadMojo.java

@Override
public void execute() throws MojoExecutionException, MojoFailureException {
    if (skipUpload) {
        getLog().info("Skipped execution");
        return;/*from w  ww  .j a v a 2 s .c  o m*/
    }
    File agentPluginArchive = getAgentPluginArchiveFile(buildDirectory, finalName);
    if (!agentPluginArchive.exists() && agentPluginArchive.isFile()) {
        throw new MojoExecutionException("Agent plugin archive does not exist: " + agentPluginArchive);
    }

    // Prepare HttpClient
    ClientConnectionManager httpConnectionManager = new BasicClientConnectionManager();
    DefaultHttpClient httpClient = new DefaultHttpClient(httpConnectionManager);
    HttpParams httpParams = httpClient.getParams();
    HttpConnectionParams.setConnectionTimeout(httpParams, socketConnectionTimeout);
    HttpConnectionParams.setSoTimeout(httpParams, socketReadTimeout);
    httpClient.getCredentialsProvider().setCredentials(new AuthScope(host, port),
            new UsernamePasswordCredentials(username, password));

    HttpPost uploadContentRequest = null;
    HttpPut moveContentToPluginsDirRequest = null;
    HttpPost pluginScanRequest = null;
    HttpPost pluginDeployRequest = null;
    HttpGet pluginDeployCheckCompleteRequest = null;
    try {

        // Upload plugin content
        URI uploadContentUri = buildUploadContentUri();
        uploadContentRequest = new HttpPost(uploadContentUri);
        uploadContentRequest.setEntity(new FileEntity(agentPluginArchive, APPLICATION_OCTET_STREAM));
        uploadContentRequest.setHeader(ACCEPT, APPLICATION_JSON.getMimeType());
        HttpResponse uploadContentResponse = httpClient.execute(uploadContentRequest);

        if (uploadContentResponse.getStatusLine().getStatusCode() != HttpStatus.SC_CREATED) {
            handleProblem(uploadContentResponse.getStatusLine().toString());
            return;
        }

        getLog().info("Uploaded " + agentPluginArchive);
        // Read the content handle value in JSON response
        JSONObject uploadContentResponseJsonObject = new JSONObject(
                EntityUtils.toString(uploadContentResponse.getEntity()));
        String contentHandle = (String) uploadContentResponseJsonObject.get("value");
        uploadContentRequest.abort();

        if (!startScan && !updatePluginsOnAllAgents) {

            // Request uploaded content to be moved to the plugins directory but do not trigger a plugin scan
            URI moveContentToPluginsDirUri = buildMoveContentToPluginsDirUri(contentHandle);
            moveContentToPluginsDirRequest = new HttpPut(moveContentToPluginsDirUri);
            moveContentToPluginsDirRequest.setHeader(ACCEPT, APPLICATION_JSON.getMimeType());
            HttpResponse moveContentToPluginsDirResponse = httpClient.execute(moveContentToPluginsDirRequest);

            if (moveContentToPluginsDirResponse.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
                handleProblem(moveContentToPluginsDirResponse.getStatusLine().toString());
                return;
            }

            moveContentToPluginsDirRequest.abort();
            getLog().info("Moved uploaded content to plugins directory");
            return;
        }

        // Request uploaded content to be moved to the plugins directory and trigger a plugin scan
        URI pluginScanUri = buildPluginScanUri(contentHandle);
        pluginScanRequest = new HttpPost(pluginScanUri);
        pluginScanRequest.setHeader(ACCEPT, APPLICATION_JSON.getMimeType());
        getLog().info("Moving uploaded content to plugins directory and requesting a plugin scan");
        HttpResponse pluginScanResponse = httpClient.execute(pluginScanRequest);

        if (pluginScanResponse.getStatusLine().getStatusCode() != HttpStatus.SC_CREATED //
                && pluginScanResponse.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
            handleProblem(pluginScanResponse.getStatusLine().toString());
            return;
        }

        pluginScanRequest.abort();
        getLog().info("Plugin scan complete");

        if (updatePluginsOnAllAgents) {

            URI pluginDeployUri = buildPluginDeployUri();
            pluginDeployRequest = new HttpPost(pluginDeployUri);
            pluginDeployRequest.setHeader(ACCEPT, APPLICATION_JSON.getMimeType());
            getLog().info("Requesting agents to update their plugins");
            HttpResponse pluginDeployResponse = httpClient.execute(pluginDeployRequest);

            if (pluginDeployResponse.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
                handleProblem(pluginDeployResponse.getStatusLine().toString());
                return;
            }

            getLog().info("Plugins update requests sent");
            // Read the agent plugins update handle value in JSON response
            JSONObject pluginDeployResponseJsonObject = new JSONObject(
                    EntityUtils.toString(pluginDeployResponse.getEntity()));
            String pluginsUpdateHandle = (String) pluginDeployResponseJsonObject.get("value");
            pluginDeployRequest.abort();

            if (waitForPluginsUpdateOnAllAgents) {

                getLog().info("Waiting for plugins update requests to complete");

                long start = System.currentTimeMillis();
                for (;;) {

                    URI pluginDeployCheckCompleteUri = buildPluginDeployCheckCompleteUri(pluginsUpdateHandle);
                    pluginDeployCheckCompleteRequest = new HttpGet(pluginDeployCheckCompleteUri);
                    pluginDeployCheckCompleteRequest.setHeader(ACCEPT, APPLICATION_JSON.getMimeType());
                    HttpResponse pluginDeployCheckCompleteResponse = httpClient
                            .execute(pluginDeployCheckCompleteRequest);

                    if (pluginDeployCheckCompleteResponse.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
                        handleProblem(pluginDeployCheckCompleteResponse.getStatusLine().toString());
                        return;
                    }

                    // Read the agent plugins update handle value in JSON response
                    JSONObject pluginDeployCheckCompleteResponseJsonObject = new JSONObject(
                            EntityUtils.toString(pluginDeployCheckCompleteResponse.getEntity()));
                    Boolean pluginDeployCheckCompleteHandle = (Boolean) pluginDeployCheckCompleteResponseJsonObject
                            .get("value");
                    pluginDeployCheckCompleteRequest.abort();

                    if (pluginDeployCheckCompleteHandle == TRUE) {
                        getLog().info("All agents updated their plugins");
                        return;
                    }

                    if (SECONDS.toMillis(
                            maxWaitForPluginsUpdateOnAllAgents) < (System.currentTimeMillis() - start)) {
                        handleProblem("Not all agents updated their plugins but wait limit has been reached ("
                                + maxWaitForPluginsUpdateOnAllAgents + " ms)");
                        return;
                    }

                    Thread.sleep(SECONDS.toMillis(5));
                    getLog().info("Checking plugins update requests status again");
                }
            }
        }
    } catch (IOException e) {
        handleException(e);
    } catch (JSONException e) {
        handleException(e);
    } catch (URISyntaxException e) {
        handleException(e);
    } catch (InterruptedException e) {
        handleException(e);
    } finally {
        abortQuietly(uploadContentRequest);
        abortQuietly(moveContentToPluginsDirRequest);
        abortQuietly(pluginScanRequest);
        abortQuietly(pluginDeployRequest);
        abortQuietly(pluginDeployCheckCompleteRequest);
        httpConnectionManager.shutdown();
    }
}

From source file:org.sonatype.nexus.plugins.webhook.WebHookNotifier.java

/**
 * Instantiate a new {@link HttpClient} instance, configured to accept all SSL certificates, and use proxy settings
 * from Nexus./*from w w w . j  av  a  2 s.c  o  m*/
 * 
 * @return an {@link HttpClient} instance - won't be null
 */
private HttpClient instantiateHttpClient() {
    DefaultHttpClient httpClient = new DefaultHttpClient();

    // configure user-agent
    HttpProtocolParams.setUserAgent(httpClient.getParams(), "Nexus WebHook Plugin");

    // configure SSL
    SSLSocketFactory socketFactory = null;
    try {
        socketFactory = new SSLSocketFactory(new TrustStrategy() {

            public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                return true;
            }
        }, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    } catch (KeyManagementException e) {
        throw new RuntimeException(e);
    } catch (UnrecoverableKeyException e) {
        throw new RuntimeException(e);
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException(e);
    } catch (KeyStoreException e) {
        throw new RuntimeException(e);
    }
    httpClient.getConnectionManager().getSchemeRegistry().register(new Scheme("https", 443, socketFactory));

    // configure proxy
    if (proxySettings != null && proxySettings.isEnabled()) {
        HttpHost proxy = new HttpHost(proxySettings.getHostname(), proxySettings.getPort());
        if (UsernamePasswordRemoteAuthenticationSettings.class
                .isInstance(proxySettings.getProxyAuthentication())) {
            UsernamePasswordRemoteAuthenticationSettings proxyAuthentication = (UsernamePasswordRemoteAuthenticationSettings) proxySettings
                    .getProxyAuthentication();
            httpClient.getCredentialsProvider().setCredentials(
                    new AuthScope(proxySettings.getHostname(), proxySettings.getPort()),
                    new UsernamePasswordCredentials(proxyAuthentication.getUsername(),
                            proxyAuthentication.getPassword()));
        }
        httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
    }

    return httpClient;
}

From source file:org.talend.core.nexus.HttpClientTransport.java

public void doRequestOne(IProgressMonitor monitor, final URI requestURI) throws Exception {
    if (monitor == null) {
        monitor = new NullProgressMonitor();
    }/*from  w  ww .ja  va2 s  .  co  m*/
    if (monitor.isCanceled()) {
        throw new OperationCanceledException();
    }
    if (requestURI == null) {
        return;
    }
    DefaultHttpClient httpClient = new DefaultHttpClient();

    IProxySelectorProvider proxySelectorProvider = null;
    try {
        if (StringUtils.isNotBlank(username)) { // set username
            httpClient.getCredentialsProvider().setCredentials(
                    new AuthScope(requestURI.getHost(), requestURI.getPort()),
                    new UsernamePasswordCredentials(username, password));
        }
        int timeout = NexusServerUtils.getTimeout();
        IDesignerCoreService designerCoreService = CoreRuntimePlugin.getInstance().getDesignerCoreService();
        if (designerCoreService != null) {
            timeout = designerCoreService.getTACConnectionTimeout() * 1000;
        }
        HttpParams params = httpClient.getParams();
        params.setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, timeout);
        params.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, timeout);

        proxySelectorProvider = addProxy(httpClient, requestURI);
        HttpResponse response = execute(monitor, httpClient, requestURI);

        processResponseCode(response);
    } catch (org.apache.http.conn.HttpHostConnectException e) {
        // connection failure
        throw e;
    } catch (java.net.SocketTimeoutException e) {
        // Read timed out
        throw e;
    } catch (Exception e) {
        throw new Exception(requestURI.toString(), e);
    } finally {
        httpClient.getConnectionManager().shutdown();
        removeProxy(proxySelectorProvider);
    }
}

From source file:org.talend.core.nexus.HttpClientTransport.java

private IProxySelectorProvider addProxy(final DefaultHttpClient httpClient, URI requestURI) {
    IProxySelectorProvider proxySelectorProvider = null;
    try {//from   ww w.  j  ava 2s  .  c  o  m
        if (Boolean.valueOf(
                System.getProperty(PROP_PROXY_HTTP_CLIENT_USE_DEFAULT_SETTINGS, Boolean.FALSE.toString()))) {
            return proxySelectorProvider;
        }
        final List<Proxy> proxyList = TalendProxySelector.getInstance().getDefaultProxySelector()
                .select(requestURI);
        Proxy usedProxy = null;
        if (proxyList != null && !proxyList.isEmpty()) {
            usedProxy = proxyList.get(0);
        }

        if (usedProxy != null) {
            if (Type.DIRECT.equals(usedProxy.type())) {
                return proxySelectorProvider;
            }
            final Proxy finalProxy = usedProxy;
            InetSocketAddress address = (InetSocketAddress) finalProxy.address();
            String proxyServer = address.getHostName();
            int proxyPort = address.getPort();
            PasswordAuthentication proxyAuthentication = Authenticator.requestPasswordAuthentication(
                    proxyServer, address.getAddress(), proxyPort, "Http Proxy", "Http proxy authentication",
                    null);
            if (proxyAuthentication != null) {
                String proxyUser = proxyAuthentication.getUserName();
                if (StringUtils.isNotBlank(proxyUser)) {
                    String proxyPassword = "";
                    char[] passwordChars = proxyAuthentication.getPassword();
                    if (passwordChars != null) {
                        proxyPassword = new String(passwordChars);
                    }
                    httpClient.getCredentialsProvider().setCredentials(new AuthScope(proxyServer, proxyPort),
                            new UsernamePasswordCredentials(proxyUser, proxyPassword));
                }
            }
            HttpHost proxyHost = new HttpHost(proxyServer, proxyPort);
            httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxyHost);
            proxySelectorProvider = createProxySelectorProvider();
        }
        return proxySelectorProvider;
    } finally {
        if (proxySelectorProvider != null) {
            TalendProxySelector.getInstance().addProxySelectorProvider(proxySelectorProvider);
        }
    }
}

From source file:org.wso2.carbon.appmgt.keymgt.service.APIKeyMgtSubscriberService.java

/**
 * Renew the ApplicationAccesstoken, Call Token endpoint and get parameters.
 * Revoke old token.//  w  w  w .  ja va  2 s .  c  o  m
 * 
 * @param tokenType
 * @param oldAccessToken
 * @param allowedDomains
 * @param clientId
 * @param clientSecret
 * @param validityTime
 * @return
 * @throws Exception
 */

public String renewAccessToken(String tokenType, String oldAccessToken, String[] allowedDomains,
        String clientId, String clientSecret, String validityTime) throws Exception {
    String newAccessToken = null;
    long validityPeriod = 0;
    // create a post request to getNewAccessToken for client_credentials
    // grant type.

    //String tokenEndpoint = OAuthServerConfiguration.getInstance().getTokenEndPoint();
    String tokenEndpointName = ServiceReferenceHolder.getInstance().getAPIManagerConfigurationService()
            .getAPIManagerConfiguration().getFirstProperty(AppMConstants.API_KEY_MANAGER_TOKEN_ENDPOINT_NAME);
    String keyMgtServerURL = ServiceReferenceHolder.getInstance().getAPIManagerConfigurationService()
            .getAPIManagerConfiguration().getFirstProperty(AppMConstants.API_KEY_MANAGER_URL);
    URL keymgtURL = new URL(keyMgtServerURL);
    int keyMgtPort = keymgtURL.getPort();
    String tokenEndpoint = null;

    if (keyMgtServerURL != null) {
        String[] tmp = keyMgtServerURL.split("services");
        tokenEndpoint = tmp[0] + tokenEndpointName;
    }

    String revokeEndpoint = tokenEndpoint.replace("token", "revoke");

    // Below code is to overcome host name verification failure we get in certificate
    // validation due to self-signed certificate.
    X509HostnameVerifier hostnameVerifier = SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;
    DefaultHttpClient client = new DefaultHttpClient();
    SchemeRegistry registry = new SchemeRegistry();
    SSLSocketFactory socketFactory = SSLSocketFactory.getSocketFactory();
    socketFactory.setHostnameVerifier(hostnameVerifier);
    if (keyMgtPort >= 0) {
        registry.register(new Scheme("https", keyMgtPort, socketFactory));
    } else {
        registry.register(new Scheme("https", 443, socketFactory));
    }
    SingleClientConnManager mgr1 = new SingleClientConnManager(registry);
    SingleClientConnManager mgr2 = new SingleClientConnManager(registry);

    HttpClient tokenEPClient = new DefaultHttpClient(mgr1, client.getParams());
    HttpClient revokeEPClient = new DefaultHttpClient(mgr2, client.getParams());
    HttpPost httpTokpost = new HttpPost(tokenEndpoint);
    HttpPost httpRevokepost = new HttpPost(revokeEndpoint);

    // Request parameters.
    List<NameValuePair> tokParams = new ArrayList<NameValuePair>(3);
    List<NameValuePair> revokeParams = new ArrayList<NameValuePair>(3);

    tokParams.add(new BasicNameValuePair(OAuth.OAUTH_GRANT_TYPE, GRANT_TYPE_CLIENT_CREDENTIALS));
    tokParams.add(new BasicNameValuePair(OAuth.OAUTH_CLIENT_ID, clientId));
    tokParams.add(new BasicNameValuePair(OAuth.OAUTH_CLIENT_SECRET, clientSecret));

    revokeParams.add(new BasicNameValuePair(OAuth.OAUTH_CLIENT_ID, clientId));
    revokeParams.add(new BasicNameValuePair(OAuth.OAUTH_CLIENT_SECRET, clientSecret));
    revokeParams.add(new BasicNameValuePair("token", oldAccessToken));

    try {
        //Revoke the Old Access Token
        httpRevokepost.setEntity(new UrlEncodedFormEntity(revokeParams, "UTF-8"));
        HttpResponse revokeResponse = tokenEPClient.execute(httpRevokepost);

        if (revokeResponse.getStatusLine().getStatusCode() != 200) {
            throw new RuntimeException(
                    "Failed : HTTP error code : " + revokeResponse.getStatusLine().getStatusCode());
        } else {
            if (log.isDebugEnabled()) {
                log.debug("Successfully revoked old application access token");
            }
        }

        //Generate New Access Token
        httpTokpost.setEntity(new UrlEncodedFormEntity(tokParams, "UTF-8"));
        HttpResponse tokResponse = revokeEPClient.execute(httpTokpost);
        HttpEntity tokEntity = tokResponse.getEntity();

        if (tokResponse.getStatusLine().getStatusCode() != 200) {
            throw new RuntimeException(
                    "Failed : HTTP error code : " + tokResponse.getStatusLine().getStatusCode());
        } else {
            String responseStr = EntityUtils.toString(tokEntity);
            JSONObject obj = new JSONObject(responseStr);
            newAccessToken = obj.get(OAUTH_RESPONSE_ACCESSTOKEN).toString();
            validityPeriod = Long.parseLong(obj.get(OAUTH_RESPONSE_EXPIRY_TIME).toString());

            if (validityTime != null && !"".equals(validityTime)) {
                validityPeriod = Long.parseLong(validityTime);
            }
        }
    } catch (Exception e2) {
        String errMsg = "Error in getting new accessToken";
        log.error(errMsg);
        throw new APIKeyMgtException(errMsg, e2);

    }
    AppMDAO appMDAO = new AppMDAO();
    appMDAO.updateRefreshedApplicationAccessToken(tokenType, newAccessToken, validityPeriod);
    return newAccessToken;

}

From source file:org.wso2.carbon.registry.es.utils.EmailUtil.java

/**
 * Initializes the httpClient.//  w w w  .  ja v  a2  s  .co  m
 */
public static void initialize() throws XPathExpressionException {

    DefaultHttpClient client = new DefaultHttpClient();

    HostnameVerifier hostnameVerifier = org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;
    SSLSocketFactory socketFactory = SSLSocketFactory.getSocketFactory();
    Scheme sch = new Scheme("https", 443, socketFactory);
    ClientConnectionManager mgr = client.getConnectionManager();
    mgr.getSchemeRegistry().register(sch);
    httpClient = new DefaultHttpClient(mgr, client.getParams());

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

From source file:rapture.common.client.BaseHttpApi.java

private static HttpClient getHttpClient() {
    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);//from w w w . j a va 2 s.c o  m
    // 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(cm);
    // Use a proxy if it is defined - we need to pass this on to the
    // HttpClient
    if (System.getProperties().containsKey("http.proxyHost")) {
        String host = System.getProperty("http.proxyHost");
        String port = System.getProperty("http.proxyPort", "8080");
        HttpHost proxy = new HttpHost(host, Integer.parseInt(port));
        httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
    }
    httpClient.addRequestInterceptor(new HttpRequestInterceptor() {

        @Override
        public void process(HttpRequest request, HttpContext arg1) throws HttpException, IOException {
            if (!request.containsHeader("Accept-Encoding")) {
                request.addHeader("Accept-Encoding", "gzip");
            }
        }

    });

    httpClient.addResponseInterceptor(new HttpResponseInterceptor() {

        @Override
        public void process(final HttpResponse response, final HttpContext context)
                throws HttpException, IOException {
            if (log.isTraceEnabled()) {
                log.trace("Response Headers:");
                for (Header h : response.getAllHeaders()) {
                    log.trace(h.getName() + " : " + h.getValue());
                }
            }
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                Header ceheader = entity.getContentEncoding();
                if (ceheader != null) {
                    HeaderElement[] codecs = ceheader.getElements();
                    for (int i = 0; i < codecs.length; i++) {
                        if (codecs[i].getName().equalsIgnoreCase("gzip")) {
                            response.setEntity(new GzipDecompressingEntity(response.getEntity()));
                            return;
                        }
                    }
                }
            }
        }

    });

    return httpClient;
}