Example usage for org.apache.http.client.config RequestConfig custom

List of usage examples for org.apache.http.client.config RequestConfig custom

Introduction

In this page you can find the example usage for org.apache.http.client.config RequestConfig custom.

Prototype

public static RequestConfig.Builder custom() 

Source Link

Usage

From source file:ee.ria.xroad.proxy.clientproxy.ClientProxy.java

private void createClient() throws Exception {
    log.trace("createClient()");

    int timeout = SystemProperties.getClientProxyTimeout();
    int socketTimeout = SystemProperties.getClientProxyHttpClientTimeout();
    RequestConfig.Builder rb = RequestConfig.custom();
    rb.setConnectTimeout(timeout);/* w ww  .  j  av a 2s .  com*/
    rb.setConnectionRequestTimeout(timeout);
    rb.setSocketTimeout(socketTimeout);

    HttpClientBuilder cb = HttpClients.custom();

    HttpClientConnectionManager connectionManager = getClientConnectionManager();
    cb.setConnectionManager(connectionManager);

    if (SystemProperties.isClientUseIdleConnectionMonitor()) {
        connectionMonitor = new IdleConnectionMonitorThread(connectionManager);
        connectionMonitor
                .setIntervalMilliseconds(SystemProperties.getClientProxyIdleConnectionMonitorInterval());
        connectionMonitor.setConnectionIdleTimeMilliseconds(
                SystemProperties.getClientProxyIdleConnectionMonitorIdleTime());
    }

    cb.setDefaultRequestConfig(rb.build());

    // Disable request retry
    cb.setRetryHandler(new DefaultHttpRequestRetryHandler(0, false));

    client = cb.build();
}

From source file:com.fourspaces.couchdb.Session.java

/**
 * Constructor for obtaining a Session with an HTTP-AUTH username/password
 * and (optionally) a secure connection This isn't supported by CouchDB -
 * you need a proxy in front to use this
 *
 * @param host - hostname//from   www.j  ava 2  s . co  m
 * @param port - port to use
 * @param user - username
 * @param pass - password
 * @param usesAuth
 * @param secure - use an SSL connection?
 */
public Session(String host, int port, String user, String pass, boolean usesAuth, boolean secure) {
    this.host = host;
    this.port = port;
    this.user = user;
    this.pass = pass;
    this.usesAuth = usesAuth;
    this.secure = secure;

    PlainConnectionSocketFactory plainsf = PlainConnectionSocketFactory.getSocketFactory();
    LayeredConnectionSocketFactory sslsf = SSLConnectionSocketFactory.getSocketFactory();
    Registry<ConnectionSocketFactory> r = RegistryBuilder.<ConnectionSocketFactory>create()
            .register("http", plainsf).register("https", sslsf).build();
    this.connManager = new PoolingHttpClientConnectionManager(r);

    this.requestConfig = RequestConfig.custom().setConnectTimeout(15 * 1000).setSocketTimeout((30 * 1000))
            .setAuthenticationEnabled(usesAuth).build();

    this.httpContext = HttpClientContext.create();
    if (user != null) {
        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(user, pass));
        this.httpContext.setCredentialsProvider(credsProvider);
    }

    this.httpClient = createHttpClient();
}

From source file:com.openshift.internal.restclient.authorization.AuthorizationClient.java

private IAuthorizationContext getContextUsingCredentials(final String baseURL,
        CredentialsProvider credentialsProvider) {

    CloseableHttpResponse response = null;
    CloseableHttpClient client = null;/*from w  w w. jav  a 2 s .  co  m*/
    try {
        OpenShiftAuthorizationRedirectStrategy redirectStrategy = new OpenShiftAuthorizationRedirectStrategy(
                openshiftClient);
        RequestConfig defaultRequestConfig = RequestConfig.custom().setSocketTimeout(TIMEOUT)
                .setConnectTimeout(TIMEOUT).setConnectionRequestTimeout(TIMEOUT)
                .setStaleConnectionCheckEnabled(true).build();
        client = HttpClients.custom().setRedirectStrategy(redirectStrategy)
                .setRoutePlanner(new SystemDefaultRoutePlanner(ProxySelector.getDefault()))
                .setHostnameVerifier(hostnameVerifier).setDefaultCredentialsProvider(credentialsProvider)
                .setSslcontext(sslContext).setDefaultRequestConfig(defaultRequestConfig).build();
        HttpGet request = new HttpGet(new URIBuilder(String.format("%s/oauth/authorize", baseURL))
                .addParameter("response_type", "token")
                .addParameter("client_id", "openshift-challenging-client").build());
        request.addHeader("X-CSRF-Token", "1");
        response = client.execute(request);
        return redirectStrategy.getAuthorizationContext();
    } catch (URISyntaxException e) {
        throw new OpenShiftException(e, String
                .format("Unvalid URI while trying to get an authorization context for server %s", baseURL));
    } catch (ClientProtocolException e) {
        throw new OpenShiftException(e, String.format(
                "Client protocol exception while trying to get authorization context for server %s", baseURL));
    } catch (IOException e) {
        throw new OpenShiftException(e,
                String.format("%s while trying to get an authorization context for server %s",
                        e.getClass().getName(), baseURL));
    } finally {
        close(response);
        close(client);
    }

}

From source file:com.vaushell.superpipes.tools.HTTPhelper.java

/**
 * Is a URI exist (HTTP response code between 200 and 299).
 *
 * @param client HTTP client./*from  w w  w  .  j  ava  2  s. c  om*/
 * @param uri the URI.
 * @param timeout how many ms to wait ? (could be null)
 * @return true if it exists.
 * @throws IOException
 */
public static boolean isURIvalid(final CloseableHttpClient client, final URI uri, final Duration timeout)
        throws IOException {
    if (client == null || uri == null) {
        throw new IllegalArgumentException();
    }

    HttpEntity responseEntity = null;
    try {
        // Exec request
        final HttpGet get = new HttpGet(uri);

        if (timeout != null && timeout.getMillis() > 0L) {
            get.setConfig(RequestConfig.custom().setConnectTimeout((int) timeout.getMillis())
                    .setConnectionRequestTimeout((int) timeout.getMillis())
                    .setSocketTimeout((int) timeout.getMillis()).build());
        }

        try (final CloseableHttpResponse response = client.execute(get)) {
            final StatusLine sl = response.getStatusLine();
            responseEntity = response.getEntity();

            return sl.getStatusCode() >= 200 && sl.getStatusCode() < 300;
        }
    } finally {
        if (responseEntity != null) {
            EntityUtils.consumeQuietly(responseEntity);
        }
    }
}

From source file:ee.ria.xroad.proxy.serverproxy.HttpClientCreator.java

private void build() throws HttpClientCreatorException {
    RegistryBuilder<ConnectionSocketFactory> sfr = RegistryBuilder.create();
    sfr.register("http", PlainConnectionSocketFactory.INSTANCE);

    try {//from  www .  jav  a2  s.com
        sfr.register("https", createSSLSocketFactory());
    } catch (Exception e) {
        throw new HttpClientCreatorException("Creating SSL Socket Factory failed", e);
    }

    connectionManager = new PoolingHttpClientConnectionManager(sfr.build());
    connectionManager.setMaxTotal(CLIENT_MAX_TOTAL_CONNECTIONS);
    connectionManager.setDefaultMaxPerRoute(CLIENT_MAX_CONNECTIONS_PER_ROUTE);
    connectionManager.setDefaultSocketConfig(SocketConfig.custom().setTcpNoDelay(true).build());

    RequestConfig.Builder rb = RequestConfig.custom();
    rb.setConnectTimeout(CLIENT_TIMEOUT);
    rb.setConnectionRequestTimeout(CLIENT_TIMEOUT);
    rb.setSocketTimeout(CLIENT_TIMEOUT);

    HttpClientBuilder cb = HttpClients.custom();
    cb.setDefaultRequestConfig(rb.build());
    cb.setConnectionManager(connectionManager);

    // Disable request retry
    cb.setRetryHandler(new DefaultHttpRequestRetryHandler(0, false));

    httpClient = cb.build();
}

From source file:tech.sirwellington.alchemy.http.AlchemyHttpBuilder.java

private static HttpClient createDefaultApacheClient(int timeout, TimeUnit timeUnit) {
    int actualTimeout = (int) TimeUnit.SECONDS.toMillis(timeout);

    //I really hate that they don't specify the expected Unit for the Timeout.
    RequestConfig config = RequestConfig.custom().setSocketTimeout(actualTimeout)
            .setConnectTimeout(actualTimeout).setConnectionRequestTimeout(actualTimeout).build();

    return HttpClientBuilder.create().setDefaultRequestConfig(config).build();
}

From source file:org.apache.manifoldcf.authorities.authorities.jira.JiraSession.java

/**
 * Constructor. Create a session./*from w  w w .  ja v a 2s .c  o  m*/
 */
public JiraSession(String clientId, String clientSecret, String protocol, String host, int port, String path,
        String proxyHost, int proxyPort, String proxyDomain, String proxyUsername, String proxyPassword)
        throws ManifoldCFException {
    this.host = new HttpHost(host, port, protocol);
    this.path = path;
    this.clientId = clientId;
    this.clientSecret = clientSecret;

    int socketTimeout = 900000;
    int connectionTimeout = 60000;

    javax.net.ssl.SSLSocketFactory httpsSocketFactory = KeystoreManagerFactory.getTrustingSecureSocketFactory();
    SSLConnectionSocketFactory myFactory = new SSLConnectionSocketFactory(
            new InterruptibleSocketFactory(httpsSocketFactory, connectionTimeout),
            SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

    connectionManager = new PoolingHttpClientConnectionManager();

    CredentialsProvider credentialsProvider = new BasicCredentialsProvider();

    // If authentication needed, set that
    if (clientId != null) {
        credentialsProvider.setCredentials(AuthScope.ANY,
                new UsernamePasswordCredentials(clientId, clientSecret));
    }

    RequestConfig.Builder requestBuilder = RequestConfig.custom().setCircularRedirectsAllowed(true)
            .setSocketTimeout(socketTimeout).setStaleConnectionCheckEnabled(true).setExpectContinueEnabled(true)
            .setConnectTimeout(connectionTimeout).setConnectionRequestTimeout(socketTimeout);

    // If there's a proxy, set that too.
    if (proxyHost != null && proxyHost.length() > 0) {

        // Configure proxy authentication
        if (proxyUsername != null && proxyUsername.length() > 0) {
            if (proxyPassword == null)
                proxyPassword = "";
            if (proxyDomain == null)
                proxyDomain = "";

            credentialsProvider.setCredentials(new AuthScope(proxyHost, proxyPort),
                    new NTCredentials(proxyUsername, proxyPassword, currentHost, proxyDomain));
        }

        HttpHost proxy = new HttpHost(proxyHost, proxyPort);
        requestBuilder.setProxy(proxy);
    }

    httpClient = HttpClients.custom().setConnectionManager(connectionManager).setMaxConnTotal(1)
            .disableAutomaticRetries().setDefaultRequestConfig(requestBuilder.build())
            .setDefaultSocketConfig(
                    SocketConfig.custom().setTcpNoDelay(true).setSoTimeout(socketTimeout).build())
            .setDefaultCredentialsProvider(credentialsProvider).setSSLSocketFactory(myFactory)
            .setRequestExecutor(new HttpRequestExecutor(socketTimeout))
            .setRedirectStrategy(new DefaultRedirectStrategy()).build();

}

From source file:org.apache.manifoldcf.crawler.connectors.confluence.ConfluenceSession.java

public ConfluenceSession(String clientId, String clientSecret, String protocol, String host, int port,
        String path, String proxyHost, int proxyPort, String proxyDomain, String proxyUsername,
        String proxyPassword) throws ManifoldCFException {
    this.host = new HttpHost(host, port, protocol);
    this.path = path;
    this.clientId = clientId;
    this.clientSecret = clientSecret;

    int socketTimeout = 900000;
    int connectionTimeout = 60000;

    javax.net.ssl.SSLSocketFactory httpsSocketFactory = KeystoreManagerFactory.getTrustingSecureSocketFactory();
    SSLConnectionSocketFactory myFactory = new SSLConnectionSocketFactory(
            new InterruptibleSocketFactory(httpsSocketFactory, connectionTimeout),
            SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

    connectionManager = new PoolingHttpClientConnectionManager();

    CredentialsProvider credentialsProvider = new BasicCredentialsProvider();

    // If authentication needed, set that
    if (clientId != null) {
        credentialsProvider.setCredentials(AuthScope.ANY,
                new UsernamePasswordCredentials(clientId, clientSecret));
    }// w  w w .  java 2s  .  c  o  m

    RequestConfig.Builder requestBuilder = RequestConfig.custom().setCircularRedirectsAllowed(true)
            .setSocketTimeout(socketTimeout).setStaleConnectionCheckEnabled(true).setExpectContinueEnabled(true)
            .setConnectTimeout(connectionTimeout).setConnectionRequestTimeout(socketTimeout);

    // If there's a proxy, set that too.
    if (proxyHost != null && proxyHost.length() > 0) {

        // Configure proxy authentication
        if (proxyUsername != null && proxyUsername.length() > 0) {
            if (proxyPassword == null)
                proxyPassword = "";
            if (proxyDomain == null)
                proxyDomain = "";

            credentialsProvider.setCredentials(new AuthScope(proxyHost, proxyPort),
                    new NTCredentials(proxyUsername, proxyPassword, currentHost, proxyDomain));
        }

        HttpHost proxy = new HttpHost(proxyHost, proxyPort);
        requestBuilder.setProxy(proxy);
    }

    httpClient = HttpClients.custom().setConnectionManager(connectionManager).setMaxConnTotal(1)
            .disableAutomaticRetries().setDefaultRequestConfig(requestBuilder.build())
            .setDefaultSocketConfig(
                    SocketConfig.custom().setTcpNoDelay(true).setSoTimeout(socketTimeout).build())
            .setDefaultCredentialsProvider(credentialsProvider).setSSLSocketFactory(myFactory)
            .setRequestExecutor(new HttpRequestExecutor(socketTimeout))
            .setRedirectStrategy(new DefaultRedirectStrategy()).build();
}

From source file:tools.devnull.boteco.client.rest.impl.DefaultRestConfiguration.java

@Override
public RestConfiguration timeoutIn(int amount, TimeUnit unit) {
    int timeout = (int) unit.toMillis(amount);
    this.request.setConfig(RequestConfig.custom().setConnectionRequestTimeout(timeout)
            .setConnectTimeout(timeout).setSocketTimeout(timeout).build());
    return this;
}

From source file:org.eclipse.jgit.transport.http.apache.HttpClientConnection.java

private HttpClient getClient() {
    if (client == null) {
        HttpClientBuilder clientBuilder = HttpClients.custom();
        RequestConfig.Builder configBuilder = RequestConfig.custom();
        if (proxy != null && !Proxy.NO_PROXY.equals(proxy)) {
            isUsingProxy = true;//from   ww  w .  j  a va2  s  .c  o m
            InetSocketAddress adr = (InetSocketAddress) proxy.address();
            clientBuilder.setProxy(new HttpHost(adr.getHostName(), adr.getPort()));
        }
        if (timeout != null) {
            configBuilder.setConnectTimeout(timeout.intValue());
        }
        if (readTimeout != null) {
            configBuilder.setSocketTimeout(readTimeout.intValue());
        }
        if (followRedirects != null) {
            configBuilder.setRedirectsEnabled(followRedirects.booleanValue());
        }
        if (hostnameverifier != null) {
            SSLConnectionSocketFactory sslConnectionFactory = new SSLConnectionSocketFactory(getSSLContext(),
                    hostnameverifier);
            clientBuilder.setSSLSocketFactory(sslConnectionFactory);
            Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
                    .register("https", sslConnectionFactory)
                    .register("http", PlainConnectionSocketFactory.INSTANCE).build();
            clientBuilder.setConnectionManager(new BasicHttpClientConnectionManager(registry));
        }
        clientBuilder.setDefaultRequestConfig(configBuilder.build());
        client = clientBuilder.build();
    }

    return client;
}