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

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

Introduction

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

Prototype

public HttpClient(HttpClientParams paramHttpClientParams) 

Source Link

Usage

From source file:com.mindquarry.common.index.SolrIndexClient.java

/**
 * Used to initialize the HTTP client.//from w  w  w .  ja  v  a 2 s  .c om
 */
public void initialize() throws Exception {
    MultiThreadedHttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager();
    httpClient = new HttpClient(connectionManager);

    // enable Preemptive authentication to save one round trip
    httpClient.getParams().setAuthenticationPreemptive(true);

    Credentials solrCreds = new UsernamePasswordCredentials(solrLogin, solrPassword);
    AuthScope anyAuthScope = new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM);

    httpClient.getState().setCredentials(anyAuthScope, solrCreds);

    // register events by calling base class initialization
    super.initialize();
}

From source file:com.atlassian.connector.intellij.util.HttpClientFactory.java

public static HttpClient getClient() throws HttpProxySettingsException {
    HttpClient httpClient = new HttpClient(connectionManager);
    httpClient.getParams().setConnectionManagerTimeout(getConnectionManagerTimeout());
    httpClient.getParams().setSoTimeout(getDataTimeout());
    HttpConfigurableAdapter httpConfigurableAdapter = ConfigurationFactory.getConfiguration()
            .transientGetHttpConfigurable();
    boolean useIdeaProxySettings = ConfigurationFactory.getConfiguration().getGeneralConfigurationData()
            .getUseIdeaProxySettings();/*from   w ww  .j a v a  2 s. c  om*/
    if (useIdeaProxySettings && (httpConfigurableAdapter != null)) {
        if (httpConfigurableAdapter.isUseHttpProxy()) {
            httpClient.getHostConfiguration().setProxy(httpConfigurableAdapter.getProxyHost(),
                    httpConfigurableAdapter.getProxyPort());
            if (httpConfigurableAdapter.isProxyAuthentication()) {

                if (httpConfigurableAdapter.getPlainProxyPassword().length() == 0
                        && !httpConfigurableAdapter.isKeepProxyPassowrd()) { //ask user for proxy passowrd

                    throw new HttpProxySettingsException("HTTP Proxy password is incorrect");
                }

                Credentials creds = null;

                //
                // code below stolen from AXIS: /transport/http/CommonsHTTPSender.java
                //
                String proxyUser = httpConfigurableAdapter.getProxyLogin();
                int domainIndex = proxyUser.indexOf("\\");
                if (domainIndex > 0) {
                    // if the username is in the form "user\domain"
                    // then use NTCredentials instead of UsernamePasswordCredentials
                    String domain = proxyUser.substring(0, domainIndex);
                    if (proxyUser.length() > domainIndex + 1) {
                        String user = proxyUser.substring(domainIndex + 1);
                        creds = new NTCredentials(user, httpConfigurableAdapter.getPlainProxyPassword(),
                                httpConfigurableAdapter.getProxyHost(), domain);
                    }
                } else {
                    creds = new UsernamePasswordCredentials(proxyUser,
                            httpConfigurableAdapter.getPlainProxyPassword());
                }
                //
                // end of code stolen from AXIS
                //

                httpClient.getState().setProxyCredentials(new AuthScope(httpConfigurableAdapter.getProxyHost(),
                        httpConfigurableAdapter.getProxyPort()), creds);
            }
        }
    }

    return httpClient;
}

From source file:com.discursive.jccook.httpclient.MultithreadedExample.java

public void start() throws InterruptedException {
    HttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager();

    HttpConnectionManagerParams params = connectionManager.getParams();
    params.setIntParameter(HttpConnectionManagerParams.MAX_HOST_CONNECTIONS, 2);
    params.setIntParameter(HttpConnectionManagerParams.MAX_TOTAL_CONNECTIONS, 4);

    List retrievers = new ArrayList();

    for (int i = 0; i < 20; i++) {
        HttpClient client = new HttpClient(connectionManager);
        Thread thread = new Thread(new PageRetriever(client));
        retrievers.add(thread);//from   w  ww .j a v  a 2s.  c o  m
    }

    Iterator threadIter = retrievers.iterator();
    while (threadIter.hasNext()) {
        Thread thread = (Thread) threadIter.next();
        thread.start();
    }
}

From source file:com.liferay.portal.search.solr.server.BasicAuthSolrServer.java

public BasicAuthSolrServer(AuthScope authScope, String username, String password, String url)
        throws MalformedURLException {

    _username = username;//w ww  .j  ava 2  s . com
    _password = password;

    _multiThreadedHttpConnectionManager = new MultiThreadedHttpConnectionManager();

    HttpClient httpClient = new HttpClient(_multiThreadedHttpConnectionManager);

    if ((_username != null) && (_password != null)) {
        if (authScope == null) {
            authScope = AuthScope.ANY;
        }

        HttpState httpState = httpClient.getState();

        httpState.setCredentials(authScope, new UsernamePasswordCredentials(_username, _password));

        HttpClientParams httpClientParams = httpClient.getParams();

        httpClientParams.setAuthenticationPreemptive(true);
    }

    _server = new CommonsHttpSolrServer(url, httpClient);
}

From source file:example.nz.org.take.compiler.userv.main.DUIConvictionInfoSource.java

@Override
public ResourceIterator<hasBeenConvictedOfaDUI> fetch(Driver driver) {

    HttpClient client = new HttpClient(new MultiThreadedHttpConnectionManager());
    client.getHttpConnectionManager().getParams().setConnectionTimeout(30000);
    GetMethod get = new GetMethod(URL);
    get.setFollowRedirects(true);/* w w w . j  a  v a2s .  c om*/
    get.setQueryString(new NameValuePair[] { new NameValuePair("id", driver.getId()) });
    try {
        logger.info("DUI conviction lookup " + get.getURI());
        client.executeMethod(get);
        String response = get.getResponseBodyAsString();
        logger.info("DUI conviction lookup result: " + response);
        if (response != null && "true".equals(response.trim())) {
            hasBeenConvictedOfaDUI record = new hasBeenConvictedOfaDUI();
            record.slot1 = driver;
            get.releaseConnection();
            return new SingletonIterator<hasBeenConvictedOfaDUI>(record);
        }
    } catch (Exception e) {
        logger.error("Error connecting to web service " + URL);
    }
    return EmptyIterator.DEFAULT;

}

From source file:edu.unc.lib.dl.ui.util.AnalyticsTrackerUtil.java

public AnalyticsTrackerUtil() {

    // Use a threaded manager with timeouts
    httpManager = new MultiThreadedHttpConnectionManager();
    httpManager.getParams().setConnectionTimeout(2000);

    httpClient = new HttpClient(httpManager);
}

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 ww  w.  ja  v  a2 s  .c  om
    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.smartitengineering.dao.solr.impl.SingletonRemoteServerFactory.java

@Override
public SolrServer getSolrServer() {
    if (solrServer == null) {
        try {//  w w  w .  j a  va  2s  .c  om
            HttpClient client = new HttpClient(new MultiThreadedHttpConnectionManager());
            CommonsHttpSolrServer commonsHttpClientSolrServer = new CommonsHttpSolrServer(
                    configuration.getUri(), client);
            commonsHttpClientSolrServer.setAllowCompression(configuration.isAllowCompression());
            commonsHttpClientSolrServer.setConnectionTimeout(configuration.getConnectionTimeout());
            commonsHttpClientSolrServer
                    .setDefaultMaxConnectionsPerHost(configuration.getDefaultMaxConnectionsPerHost());
            commonsHttpClientSolrServer.setFollowRedirects(configuration.isFollowRedirects());
            commonsHttpClientSolrServer.setMaxRetries(configuration.getMaxRetries());
            commonsHttpClientSolrServer.setMaxTotalConnections(configuration.getMaxTotalConnections());
            commonsHttpClientSolrServer.setParser(configuration.getResponseParser());
            commonsHttpClientSolrServer.setSoTimeout(configuration.getSocketTimeout());
            commonsHttpClientSolrServer.setRequestWriter(new BinaryRequestWriter());
            this.solrServer = commonsHttpClientSolrServer;
        } catch (Exception ex) {
            logger.error("Could not intialize solr server", ex);
        }
    }
    return solrServer;
}

From source file:de.michaeltamm.W3cMarkupValidator.java

/**
 * Validates the given <code>html</code>.
 *
 * @param html a complete HTML document// ww  w . j av  a  2  s  .co  m
 */
public W3cMarkupValidationResult validate(String html) {
    if (_httpClient == null) {
        final MultiThreadedHttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager();
        _httpClient = new HttpClient(connectionManager);
    }
    final PostMethod postMethod = new PostMethod(_checkUrl);
    final Part[] data = {
            // The HTML to validate ...
            new StringPart("fragment", html, "UTF-8"), new StringPart("prefill", "0", "UTF-8"),
            new StringPart("doctype", "Inline", "UTF-8"), new StringPart("prefill_doctype", "html401", "UTF-8"),
            // List Messages Sequentially | Group Error Messages by Type ...
            new StringPart("group", "0", "UTF-8"),
            // Show source ...
            new StringPart("ss", "1", "UTF-8"),
            // Verbose Output ...
            new StringPart("verbose", "1", "UTF-8"), };
    postMethod.setRequestEntity(new MultipartRequestEntity(data, postMethod.getParams()));
    try {
        final int status = _httpClient.executeMethod(postMethod);
        if (status != 200) {
            throw new RuntimeException(_checkUrl + " responded with " + status);
        }
        final String pathPrefix = _checkUrl.substring(0, _checkUrl.lastIndexOf('/') + 1);
        final String resultPage = getResponseBody(postMethod).replace("\"./", "\"" + pathPrefix)
                .replace("src=\"images/", "src=\"" + pathPrefix + "images/")
                .replace("<script type=\"text/javascript\" src=\"loadexplanation.js\">",
                        "<script type=\"text/javascript\" src=\"" + pathPrefix + "loadexplanation.js\">");
        return new W3cMarkupValidationResult(resultPage);
    } catch (RuntimeException e) {
        throw e;
    } catch (Exception e) {
        throw new RuntimeException(e.getMessage(), e);
    } finally {
        postMethod.releaseConnection();
    }
}

From source file:com.datos.vfs.provider.http.HttpClientFactory.java

/**
 * Creates a new connection to the server.
 * @param builder The HttpFileSystemConfigBuilder.
 * @param scheme The protocol.//from w  w w  . j a v  a  2 s.c  o  m
 * @param hostname The hostname.
 * @param port The port number.
 * @param username The username.
 * @param password The password
 * @param fileSystemOptions The file system options.
 * @return a new HttpClient connection.
 * @throws FileSystemException if an error occurs.
 * @since 2.0
 */
public static HttpClient createConnection(final HttpFileSystemConfigBuilder builder, final String scheme,
        final String hostname, final int port, final String username, final String password,
        final FileSystemOptions fileSystemOptions) throws FileSystemException {
    HttpClient client;
    try {
        final HttpConnectionManager mgr = new MultiThreadedHttpConnectionManager();
        final HttpConnectionManagerParams connectionMgrParams = mgr.getParams();

        client = new HttpClient(mgr);

        final HostConfiguration config = new HostConfiguration();
        config.setHost(hostname, port, scheme);

        if (fileSystemOptions != null) {
            final String proxyHost = builder.getProxyHost(fileSystemOptions);
            final int proxyPort = builder.getProxyPort(fileSystemOptions);

            if (proxyHost != null && proxyHost.length() > 0 && proxyPort > 0) {
                config.setProxy(proxyHost, proxyPort);
            }

            final UserAuthenticator proxyAuth = builder.getProxyAuthenticator(fileSystemOptions);
            if (proxyAuth != null) {
                final UserAuthenticationData authData = UserAuthenticatorUtils.authenticate(proxyAuth,
                        new UserAuthenticationData.Type[] { UserAuthenticationData.USERNAME,
                                UserAuthenticationData.PASSWORD });

                if (authData != null) {
                    final UsernamePasswordCredentials proxyCreds = new UsernamePasswordCredentials(
                            UserAuthenticatorUtils.toString(UserAuthenticatorUtils.getData(authData,
                                    UserAuthenticationData.USERNAME, null)),
                            UserAuthenticatorUtils.toString(UserAuthenticatorUtils.getData(authData,
                                    UserAuthenticationData.PASSWORD, null)));

                    final AuthScope scope = new AuthScope(proxyHost, AuthScope.ANY_PORT);
                    client.getState().setProxyCredentials(scope, proxyCreds);
                }

                if (builder.isPreemptiveAuth(fileSystemOptions)) {
                    final HttpClientParams httpClientParams = new HttpClientParams();
                    httpClientParams.setAuthenticationPreemptive(true);
                    client.setParams(httpClientParams);
                }
            }

            final Cookie[] cookies = builder.getCookies(fileSystemOptions);
            if (cookies != null) {
                client.getState().addCookies(cookies);
            }
        }
        /**
         * ConnectionManager set methods must be called after the host & port and proxy host & port
         * are set in the HostConfiguration. They are all used as part of the key when HttpConnectionManagerParams
         * tries to locate the host configuration.
         */
        connectionMgrParams.setMaxConnectionsPerHost(config,
                builder.getMaxConnectionsPerHost(fileSystemOptions));
        connectionMgrParams.setMaxTotalConnections(builder.getMaxTotalConnections(fileSystemOptions));

        connectionMgrParams.setConnectionTimeout(builder.getConnectionTimeout(fileSystemOptions));
        connectionMgrParams.setSoTimeout(builder.getSoTimeout(fileSystemOptions));

        client.setHostConfiguration(config);

        if (username != null) {
            final UsernamePasswordCredentials creds = new UsernamePasswordCredentials(username, password);
            final AuthScope scope = new AuthScope(hostname, AuthScope.ANY_PORT);
            client.getState().setCredentials(scope, creds);
        }
    } catch (final Exception exc) {
        throw new FileSystemException("vfs.provider.http/connect.error", exc, hostname);
    }

    return client;
}