Example usage for org.apache.commons.httpclient HostConfiguration HostConfiguration

List of usage examples for org.apache.commons.httpclient HostConfiguration HostConfiguration

Introduction

In this page you can find the example usage for org.apache.commons.httpclient HostConfiguration HostConfiguration.

Prototype

public HostConfiguration() 

Source Link

Usage

From source file:UsingHttpClientInsideThread.java

public static void main(String args[]) throws Exception {

    HttpClient client = new HttpClient();
    client.getParams().setParameter("http.useragent", "Test Client");

    HostConfiguration host = new HostConfiguration();
    host.setHost(new URI("http://localhost:8080", true));

    // first Get a big file
    MethodThread bigDataThread = new MethodThread(client, host, "/big_movie.wmv");

    bigDataThread.start();/*from   ww w  . j  a v  a2s  .c o m*/

    // next try and get a small file
    MethodThread normalThread = new MethodThread(client, host, "/");

    normalThread.start();
}

From source file:GetMethodExample.java

public static void main(String args[]) {

    HttpClient client = new HttpClient();
    client.getParams().setParameter("http.useragent", "Test Client");
    client.getParams().setParameter("http.connection.timeout", new Integer(5000));

    GetMethod method = new GetMethod();
    FileOutputStream fos = null;//w w w. java2 s.  c o m

    try {

        method.setURI(new URI("http://www.google.com", true));
        int returnCode = client.executeMethod(method);

        if (returnCode != HttpStatus.SC_OK) {
            System.err.println("Unable to fetch default page, status code: " + returnCode);
        }

        System.err.println(method.getResponseBodyAsString());

        method.setURI(new URI("http://www.google.com/images/logo.gif", true));
        returnCode = client.executeMethod(method);

        if (returnCode != HttpStatus.SC_OK) {
            System.err.println("Unable to fetch image, status code: " + returnCode);
        }

        byte[] imageData = method.getResponseBody();
        fos = new FileOutputStream(new File("google.gif"));
        fos.write(imageData);

        HostConfiguration hostConfig = new HostConfiguration();
        hostConfig.setHost("www.yahoo.com", null, 80, Protocol.getProtocol("http"));

        method.setURI(new URI("/", true));

        client.executeMethod(hostConfig, method);

        System.err.println(method.getResponseBodyAsString());

    } catch (HttpException he) {
        System.err.println(he);
    } catch (IOException ie) {
        System.err.println(ie);
    } finally {
        method.releaseConnection();
        if (fos != null)
            try {
                fos.close();
            } catch (Exception fe) {
            }
    }

}

From source file:fr.cls.atoll.motu.library.misc.cas.HttpClientTutorial.java

public static void main(String[] args) {

    // test();//from   www. java2s .  c  om
    // System.setProperty("proxyHost", "proxy.cls.fr"); // adresse IP
    // System.setProperty("proxyPort", "8080");
    // System.setProperty("socksProxyPort", "1080");
    //
    // Authenticator.setDefault(new MyAuthenticator());

    // Create an instance of HttpClient.
    // HttpClient client = new HttpClient();
    HttpClient client = new HttpClient(new MultiThreadedHttpConnectionManager());
    // Create a method instance.
    GetMethod method = new GetMethod(url);

    HostConfiguration hostConfiguration = new HostConfiguration();
    hostConfiguration.setProxy("proxy.cls.fr", 8080);
    client.setHostConfiguration(hostConfiguration);

    // Provide custom retry handler is necessary
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(3, false));
    // String username = "xxx";
    // String password = "xxx";
    // Credentials credentials = new UsernamePasswordCredentials(username, password);
    // AuthScope authScope = new AuthScope("proxy.cls.fr", 8080);
    //     
    // client.getState().setProxyCredentials(authScope, credentials);

    try {
        // Execute the method.
        int statusCode = client.executeMethod(method);

        if (statusCode != HttpStatus.SC_OK) {
            System.err.println("Method failed: " + method.getStatusLine());
        }

        // Read the response body.
        byte[] responseBody = method.getResponseBody();

        // Deal with the response.
        // Use caution: ensure correct character encoding and is not binary data
        System.out.println(new String(responseBody));

    } catch (HttpException e) {
        System.err.println("Fatal protocol violation: " + e.getMessage());
        e.printStackTrace();
    } catch (IOException e) {
        System.err.println("Fatal transport error: " + e.getMessage());
        e.printStackTrace();
    } finally {
        // Release the connection.
        method.releaseConnection();
    }
}

From source file:fr.dutra.confluence2wordpress.xmlrpc.CommonsXmlRpcTransportFactory.java

public CommonsXmlRpcTransportFactory(URL url, String proxyHost, int proxyPort, int maxConnections) {
    this.url = url;
    HostConfiguration hostConf = new HostConfiguration();
    hostConf.setHost(url.getHost(), url.getPort());
    if (proxyHost != null && proxyPort != -1) {
        hostConf.setProxy(proxyHost, proxyPort);
    }//from   w ww .  j  a  v a2s. c  o  m
    HttpConnectionManagerParams connParam = new HttpConnectionManagerParams();
    connParam.setMaxConnectionsPerHost(hostConf, maxConnections);
    connParam.setMaxTotalConnections(maxConnections);
    MultiThreadedHttpConnectionManager conMgr = new MultiThreadedHttpConnectionManager();
    conMgr.setParams(connParam);
    client = new HttpClient(conMgr);
    client.setHostConfiguration(hostConf);
}

From source file:com.taobao.metamorphosis.client.http.SimpleHttpClient.java

protected void initHttpClient(HttpClientConfig config) {
    HostConfiguration hostConfiguration = new HostConfiguration();
    hostConfiguration.setHost(config.getHost(), config.getPort());

    connectionManager = new MultiThreadedHttpConnectionManager();
    connectionManager.closeIdleConnections(config.getPollingIntervalTime() * 4000);

    HttpConnectionManagerParams params = new HttpConnectionManagerParams();
    params.setStaleCheckingEnabled(config.isConnectionStaleCheckingEnabled());
    params.setMaxConnectionsPerHost(hostConfiguration, config.getMaxHostConnections());
    params.setMaxTotalConnections(config.getMaxTotalConnections());
    params.setConnectionTimeout(config.getTimeout());
    params.setSoTimeout(60 * 1000);/*w  w w . j a  va2 s. c  o m*/

    connectionManager.setParams(params);
    httpclient = new HttpClient(connectionManager);
    httpclient.setHostConfiguration(hostConfiguration);
}

From source file:com.jivesoftware.os.jive.utils.http.client.ApacheHttpClient31BackedHttpClientOAuthTest.java

@BeforeMethod
public void setup() throws Exception {
    httpClient = mock(org.apache.commons.httpclient.HttpClient.class);
    when(httpClient.getHostConfiguration()).thenReturn(new HostConfiguration());
    oAuthHttpClient = new ApacheHttpClient31BackedHttpClient(httpClient, new HashMap<String, String>());
}

From source file:fr.gouv.finances.dgfip.xemelios.common.NetAccess.java

public static HttpClient getHttpClient(PropertiesExpansion applicationProperties)
        throws DataConfigurationException {
    String proxyHost = applicationProperties.getProperty(Constants.SYS_PROP_PROXY_SERVER);
    String proxyPort = applicationProperties.getProperty(Constants.SYS_PROP_PROXY_PORT);
    String proxyUser = applicationProperties.getProperty(Constants.SYS_PROP_PROXY_USER);
    String sTmp = applicationProperties.getProperty(Constants.SYS_PROP_PROXY_PASSWD);
    String proxyPasswd = sTmp != null ? Scramble.unScramblePassword(sTmp) : null;
    int intProxyPort = 0;
    if (proxyPort != null) {
        try {// w w  w  .  j a va  2s  .com
            intProxyPort = Integer.parseInt(proxyPort);
        } catch (NumberFormatException nfEx) {
            throw new DataConfigurationException(proxyPort + " n'est pas un numro de port valide.");
        }
    }
    String domainName = applicationProperties.getProperty(Constants.SYS_PROP_PROXY_DOMAIN);

    HttpClient client = new HttpClient();
    //client.getParams().setAuthenticationPreemptive(true);   // check use of this
    HostConfiguration hc = new HostConfiguration();
    if (proxyHost != null) {
        hc.setProxy(proxyHost, intProxyPort);
        client.setHostConfiguration(hc);
    }
    if (proxyUser != null) {
        Credentials creds = null;
        if (domainName != null && domainName.length() > 0) {
            String hostName = "127.0.0.1";
            try {
                InetAddress ip = InetAddress.getByName("127.0.0.1");
                hostName = ip.getHostName();
            } catch (Exception ex) {
                logger.error("", ex);
            }
            creds = new NTCredentials(proxyUser, proxyPasswd, hostName, domainName);
        } else {
            creds = new UsernamePasswordCredentials(proxyUser, proxyPasswd);
        }
        client.getState().setProxyCredentials(AuthScope.ANY, creds);
        //            client.getState().setProxyCredentials(AuthScope.ANY,new UsernamePasswordCredentials(proxyUser,proxyPasswd));
    }
    return client;
}

From source file:de.softwareforge.pgpsigner.util.HKPSender.java

public HKPSender(final String serverName) {
    HttpHost httpHost = new HttpHost(serverName, HKP_DEFAULT_PORT);
    HostConfiguration hostConfig = new HostConfiguration();
    hostConfig.setHost(httpHost);/*  w  w w.  j  a v  a  2s. c  om*/
    this.httpClient = new HttpClient();
    this.httpClient.getParams().setParameter("http.useragent", PGPSigner.APPLICATION_VERSION);
    httpClient.setHostConfiguration(hostConfig);
}

From source file:com.jivesoftware.os.jive.utils.http.client.HttpClientFactoryProvider.java

public HttpClientFactory createHttpClientFactory(final Collection<HttpClientConfiguration> configurations) {
    return new HttpClientFactory() {
        @Override//from w w w  .  j  av  a 2  s  .com
        public HttpClient createClient(String host, int port) {

            ApacheHttpClient31BackedHttpClient httpClient = createApacheClient();

            HostConfiguration hostConfiguration = new HostConfiguration();
            configureSsl(hostConfiguration, host, port, httpClient);
            configureProxy(hostConfiguration, httpClient);

            httpClient.setHostConfiguration(hostConfiguration);
            configureOAuth(httpClient);
            return httpClient;
        }

        private ApacheHttpClient31BackedHttpClient createApacheClient() {
            HttpClientConfig httpClientConfig = locateConfig(HttpClientConfig.class,
                    HttpClientConfig.newBuilder().build());

            HttpConnectionManager connectionManager = createConnectionManager(httpClientConfig);

            org.apache.commons.httpclient.HttpClient client = new org.apache.commons.httpclient.HttpClient(
                    connectionManager);
            client.getParams().setParameter(HttpMethodParams.COOKIE_POLICY, CookiePolicy.RFC_2109);
            client.getParams().setParameter(HttpMethodParams.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
            client.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8");
            client.getParams().setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE, false);
            client.getParams().setBooleanParameter(HttpConnectionParams.STALE_CONNECTION_CHECK, true);
            client.getParams().setParameter(HttpConnectionParams.CONNECTION_TIMEOUT,
                    httpClientConfig.getSocketTimeoutInMillis() > 0
                            ? httpClientConfig.getSocketTimeoutInMillis()
                            : 0);
            client.getParams().setParameter(HttpConnectionParams.SO_TIMEOUT,
                    httpClientConfig.getSocketTimeoutInMillis() > 0
                            ? httpClientConfig.getSocketTimeoutInMillis()
                            : 0);

            return new ApacheHttpClient31BackedHttpClient(client,
                    httpClientConfig.getCopyOfHeadersForEveryRequest());

        }

        @SuppressWarnings("unchecked")
        private <T> T locateConfig(Class<? extends T> _class, T defaultConfiguration) {
            for (HttpClientConfiguration configuration : configurations) {
                if (_class.isInstance(configuration)) {
                    return (T) configuration;
                }
            }
            return defaultConfiguration;
        }

        private boolean hasValidProxyUsernameAndPasswordSettings(HttpClientProxyConfig httpClientProxyConfig) {
            return StringUtils.isNotBlank(httpClientProxyConfig.getProxyUsername())
                    && StringUtils.isNotBlank(httpClientProxyConfig.getProxyPassword());
        }

        private HttpConnectionManager createConnectionManager(HttpClientConfig config) {
            MultiThreadedHttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager();
            if (config.getMaxConnectionsPerHost() > 0) {
                connectionManager.getParams()
                        .setDefaultMaxConnectionsPerHost(config.getMaxConnectionsPerHost());
            } else {
                connectionManager.getParams().setDefaultMaxConnectionsPerHost(Integer.MAX_VALUE);
            }
            if (config.getMaxConnections() > 0) {
                connectionManager.getParams().setMaxTotalConnections(config.getMaxConnections());
            }
            return connectionManager;
        }

        private void configureOAuth(ApacheHttpClient31BackedHttpClient httpClient) {
            HttpClientOAuthConfig httpClientOAuthConfig = locateConfig(HttpClientOAuthConfig.class, null);
            if (httpClientOAuthConfig != null) {
                String serviceName = httpClientOAuthConfig.getServiceName();
                HttpClientConsumerKeyAndSecretProvider consumerKeyAndSecretProvider = httpClientOAuthConfig
                        .getConsumerKeyAndSecretProvider();
                String consumerKey = consumerKeyAndSecretProvider.getConsumerKey(serviceName);
                if (StringUtils.isEmpty(consumerKey)) {
                    throw new RuntimeException(
                            "could create oauth client because consumerKey is null or empty for service:"
                                    + serviceName);
                }
                String consumerSecret = consumerKeyAndSecretProvider.getConsumerSecret(serviceName);
                if (StringUtils.isEmpty(consumerSecret)) {
                    throw new RuntimeException(
                            "could create oauth client because consumerSecret is null or empty for service:"
                                    + serviceName);
                }

                httpClient.setConsumerTokens(consumerKey, consumerSecret);
            }
        }

        private void configureProxy(HostConfiguration hostConfiguration,
                ApacheHttpClient31BackedHttpClient httpClient) {
            HttpClientProxyConfig httpClientProxyConfig = locateConfig(HttpClientProxyConfig.class, null);
            if (httpClientProxyConfig != null) {
                hostConfiguration.setProxy(httpClientProxyConfig.getProxyHost(),
                        httpClientProxyConfig.getProxyPort());
                if (hasValidProxyUsernameAndPasswordSettings(httpClientProxyConfig)) {
                    HttpState state = new HttpState();
                    state.setProxyCredentials(AuthScope.ANY,
                            new UsernamePasswordCredentials(httpClientProxyConfig.getProxyUsername(),
                                    httpClientProxyConfig.getProxyPassword()));
                    httpClient.setState(state);
                }
            }
        }

        private void configureSsl(HostConfiguration hostConfiguration, String host, int port,
                ApacheHttpClient31BackedHttpClient httpClient) throws IllegalStateException {
            HttpClientSSLConfig httpClientSSLConfig = locateConfig(HttpClientSSLConfig.class, null);
            if (httpClientSSLConfig != null) {
                Protocol sslProtocol;
                if (httpClientSSLConfig.getCustomSSLSocketFactory() != null) {
                    sslProtocol = new Protocol(HTTPS_PROTOCOL, new CustomSecureProtocolSocketFactory(
                            httpClientSSLConfig.getCustomSSLSocketFactory()), SSL_PORT);
                } else {
                    sslProtocol = Protocol.getProtocol(HTTPS_PROTOCOL);
                }
                hostConfiguration.setHost(host, port, sslProtocol);
                httpClient.setUsingSSL();
            } else {
                hostConfiguration.setHost(host, port);
            }
        }
    };
}

From source file:com.exalead.io.failover.MonitoredHttpConnectionManager.java

/**
 * Gets the host configuration for a connection.
 * @param conn the connection to get the configuration of
 * @return a new HostConfiguration//from   w w w. java  2s . c o  m
 */
static HostConfiguration rebuildConfigurationFromConnection(HttpConnection conn) {
    HostConfiguration connectionConfiguration = new HostConfiguration();
    connectionConfiguration.setHost(conn.getHost(), conn.getPort(), conn.getProtocol());
    if (conn.getLocalAddress() != null) {
        connectionConfiguration.setLocalAddress(conn.getLocalAddress());
    }
    if (conn.getProxyHost() != null) {
        connectionConfiguration.setProxy(conn.getProxyHost(), conn.getProxyPort());
    }
    return connectionConfiguration;
}