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:com.clxcommunications.xms.ApiHttpAsyncClient.java

/**
 * Creates a new HTTP asynchronous client suitable for communicating with
 * XMS.//from  w  w  w .j av  a 2 s. c  o  m
 * 
 * @param startedInternally
 *            whether this object was created inside this SDK
 */
ApiHttpAsyncClient(boolean startedInternally) {
    this.startedInternally = startedInternally;

    // Allow TLSv1.2 protocol only
    SSLIOSessionStrategy sslSessionStrategy = new SSLIOSessionStrategy(SSLContexts.createSystemDefault(),
            new String[] { "TLSv1.2" }, null, SSLIOSessionStrategy.getDefaultHostnameVerifier());

    RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout((int) DEFAULT_TIMEOUT.toMillis())
            .setSocketTimeout((int) DEFAULT_TIMEOUT.toMillis()).build();

    // TODO: Is this a good default setup?
    this.client = HttpAsyncClients.custom().setSSLStrategy(sslSessionStrategy).disableCookieManagement()
            .setMaxConnPerRoute(DEFAULT_MAX_CONN).setMaxConnTotal(DEFAULT_MAX_CONN)
            .setDefaultRequestConfig(requestConfig).build();
}

From source file:org.sakaiproject.contentreview.urkund.util.UrkundAPIUtil.java

public static String getFileInfo(String baseUrl, String externalId, String receiverAddress,
        String urkundUsername, String urkundPassword, int timeout) {
    String ret = null;//  ww w .j  ava  2 s .  c o m
    RequestConfig.Builder requestBuilder = RequestConfig.custom();
    requestBuilder = requestBuilder.setConnectTimeout(timeout);
    requestBuilder = requestBuilder.setConnectionRequestTimeout(timeout);

    HttpClientBuilder builder = HttpClientBuilder.create();
    builder.setDefaultRequestConfig(requestBuilder.build());
    try (CloseableHttpClient httpClient = builder.build()) {
        HttpGet httpget = new HttpGet(baseUrl + "submissions/" + receiverAddress + "/" + externalId);

        //------------------------------------------------------------
        if (StringUtils.isNotBlank(urkundUsername) && StringUtils.isNotBlank(urkundPassword)) {
            addAuthorization(httpget, urkundUsername, urkundPassword);
        }
        //------------------------------------------------------------
        httpget.addHeader("Accept", "application/json");
        //------------------------------------------------------------

        HttpResponse response = httpClient.execute(httpget);
        HttpEntity resEntity = response.getEntity();

        if (resEntity != null) {
            ret = EntityUtils.toString(resEntity);
            EntityUtils.consume(resEntity);
        }

    } catch (IOException e) {
        log.error("ERROR getting File Info : ", e);
    }
    return ret;
}

From source file:de.hsos.ecs.richwps.wpsmonitor.communication.wpsclient.defaultimpl.SimpleWpsClient.java

@Override
public void init(final WpsClientConfig config) {
    LOG.debug("Init WpsClient with {}", config);

    Integer timeout = config.getConnectionTimeout();

    RequestConfig.Builder requestBuilder = RequestConfig.custom().setConnectTimeout(timeout)
            .setSocketTimeout(timeout).setConnectionRequestTimeout(timeout);

    httpClient = HttpClientBuilder.create().setDefaultRequestConfig(requestBuilder.build()).build();
}

From source file:io.github.cidisk.indexcrawler.fetcher.PageFetcher.java

public PageFetcher(CrawlConfig config) {
    super(config);

    RequestConfig requestConfig = RequestConfig.custom().setExpectContinueEnabled(false)
            .setCookieSpec(CookieSpecs.BROWSER_COMPATIBILITY).setRedirectsEnabled(false)
            .setSocketTimeout(config.getSocketTimeout()).setConnectTimeout(config.getConnectionTimeout())
            .build();// ww w.  ja  v  a2 s  .c o  m

    RegistryBuilder<ConnectionSocketFactory> connRegistryBuilder = RegistryBuilder.create();
    connRegistryBuilder.register("http", PlainConnectionSocketFactory.INSTANCE);
    if (config.isIncludeHttpsPages()) {
        try { // Fixing: https://code.google.com/p/crawler4j/issues/detail?id=174
            // By always trusting the ssl certificate
            SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, new TrustStrategy() {
                @Override
                public boolean isTrusted(final X509Certificate[] chain, String authType) {
                    return true;
                }
            }).build();
            SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext,
                    SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
            connRegistryBuilder.register("https", sslsf);
        } catch (Exception e) {
            logger.warn("Exception thrown while trying to register https");
            logger.debug("Stacktrace", e);
        }
    }

    Registry<ConnectionSocketFactory> connRegistry = connRegistryBuilder.build();
    connectionManager = new PoolingHttpClientConnectionManager(connRegistry);
    connectionManager.setMaxTotal(config.getMaxTotalConnections());
    connectionManager.setDefaultMaxPerRoute(config.getMaxConnectionsPerHost());

    HttpClientBuilder clientBuilder = HttpClientBuilder.create();
    clientBuilder.setDefaultRequestConfig(requestConfig);
    clientBuilder.setConnectionManager(connectionManager);
    clientBuilder.setUserAgent(config.getUserAgentString());

    if (config.getProxyHost() != null) {
        if (config.getProxyUsername() != null) {
            BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
            credentialsProvider.setCredentials(new AuthScope(config.getProxyHost(), config.getProxyPort()),
                    new UsernamePasswordCredentials(config.getProxyUsername(), config.getProxyPassword()));
            clientBuilder.setDefaultCredentialsProvider(credentialsProvider);
        }

        HttpHost proxy = new HttpHost(config.getProxyHost(), config.getProxyPort());
        clientBuilder.setProxy(proxy);
        logger.debug("Working through Proxy: {}", proxy.getHostName());
    }

    httpClient = clientBuilder.build();
    if (config.getAuthInfos() != null && !config.getAuthInfos().isEmpty()) {
        doAuthetication(config.getAuthInfos());
    }

    if (connectionMonitorThread == null) {
        connectionMonitorThread = new IdleConnectionMonitorThread(connectionManager);
    }
    connectionMonitorThread.start();
}

From source file:org.workin.http.httpclient.v4.HttpClientTemplet.java

@Override
public void afterPropertiesSet() throws Exception {
    super.afterPropertiesSet();

    if (this.httpClientFactory == null)
        this.httpClientFactory = new CloseableHttpClientFactoryBean();

    if (this.requestConfig == null)
        this.requestConfig = RequestConfig.custom().build();

    if (this.requestHandler == null)
        this.requestHandler = new DefualtRequestHandler();

    if (this.responseHandler == null)
        this.responseHandler = new StringResponseHandler();
}

From source file:org.openehealth.ipf.commons.ihe.fhir.SslAwareApacheRestfulClientFactory.java

protected synchronized HttpClient getNativeHttpClient() {
    if (httpClient == null) {

        // @formatter:off
        RequestConfig defaultRequestConfig = RequestConfig.custom().setConnectTimeout(getConnectTimeout())
                .setSocketTimeout(getSocketTimeout()).setConnectionRequestTimeout(getConnectionRequestTimeout())
                .setProxy(proxy).setStaleConnectionCheckEnabled(true).build();

        HttpClientBuilder builder = HttpClients.custom().useSystemProperties()
                .setDefaultRequestConfig(defaultRequestConfig).setMaxConnTotal(getPoolMaxTotal())
                .setMaxConnPerRoute(getPoolMaxPerRoute()).setConnectionTimeToLive(5, TimeUnit.SECONDS)
                .disableCookieManagement();

        if (securityInformation != null) {
            securityInformation.configureHttpClientBuilder(builder);
        }/*from ww w .  ja  v  a 2 s . c o  m*/

        // Need to authenticate against proxy
        if (proxy != null && StringUtils.isNotBlank(getProxyUsername())
                && StringUtils.isNotBlank(getProxyPassword())) {
            CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
            credentialsProvider.setCredentials(new AuthScope(proxy.getHostName(), proxy.getPort()),
                    new UsernamePasswordCredentials(getProxyUsername(), getProxyPassword()));
            builder.setProxyAuthenticationStrategy(new ProxyAuthenticationStrategy());
            builder.setDefaultCredentialsProvider(credentialsProvider);
        }

        httpClient = builder.build();
    }

    return httpClient;
}

From source file:org.rifidi.edge.init.Activator.java

@Override
public void start(BundleContext arg0) throws Exception {

    try {/*  ww w  .j  a va 2  s  . c  o m*/
        System.out.println("START RIFIDI INITIALIZTION BUNDLE");

        boolean failoverEnabled = false;
        String primary = System.getProperty("org.rifidi.failover.primary");
        if (primary != null && !primary.equals("")) {
            failoverEnabled = true;
        }
        if (failoverEnabled) {
            System.out.println("Primary: " + primary);
            Integer failoverTrySeconds = Integer.parseInt(System.getProperty("org.rifidi.failover.frequency"));
            Integer numFailsRequired = Integer.parseInt(System.getProperty("org.rifidi.failover.failurecount"));
            for (int numFails = 0; numFails < numFailsRequired;) {
                CloseableHttpClient httpclient = null;
                try {
                    Thread.sleep(failoverTrySeconds * 1000);
                    httpclient = HttpClients.createDefault();
                    int CONNECTION_TIMEOUT_MS = 5 * 1000; // Timeout in millis.
                    RequestConfig requestConfig = RequestConfig.custom()
                            .setConnectionRequestTimeout(CONNECTION_TIMEOUT_MS)
                            .setConnectTimeout(CONNECTION_TIMEOUT_MS).setSocketTimeout(CONNECTION_TIMEOUT_MS)
                            .build();

                    HttpGet httpGet = new HttpGet("http://" + primary + "/ping");
                    httpGet.setConfig(requestConfig);
                    httpclient.execute(httpGet);

                    System.out.println("Response received from " + primary + ", sleeping for "
                            + failoverTrySeconds + " seconds");
                    // Got past the get()...reset the counter
                    if (numFails > 0) {
                        System.out.println("Request to primary " + primary
                                + " succeeded after previous failure, resetting the counter");
                        numFails = 0;
                    }
                } catch (InterruptedException e) {
                    System.out.println("Interrupted Exception -- trying again");
                    // Do nothing...wasn't a network failure
                } catch (Exception e) {
                    // Exception happened, could not connect to
                    numFails++;
                    System.out.println("Failed to connect to primary " + primary + ", incrementing counter: "
                            + numFails + " number of fails required: " + numFailsRequired);
                } finally {
                    if (httpclient != null) {
                        httpclient.close();
                    }
                }
            }

            // TODO: Call the primary here, get a response.
        }

        // look up the path to the rifidi home directory
        String rifidiHome = System.getProperty("org.rifidi.home");

        // if it's null, set it to the "user.dir" directory
        if (rifidiHome == null) {
            String userDir = System.getProperty("user.dir");
            System.setProperty("org.rifidi.home", userDir);
            rifidiHome = System.getProperty("org.rifidi.home");
        }
        System.out.println(
                "ALL RIFIDI CONFIGURATION PATHS RELATIVE TO : " + System.getProperty("org.rifidi.home"));

        // set the path to the applications folder
        System.setProperty("org.rifidi.edge.applications", "applications");

        // set up logging
        String slash = "";
        if (rifidiHome.charAt(0) != '/') {
            slash = "/";
        }
        String s = "file:" + slash + rifidiHome + System.getProperty("file.separator")
                + System.getProperty("org.rifidi.edge.logging");
        // We have to do this bit of idiocy to get URIs to work with windows
        // backslashes and "Documents and Settings".
        URI uri = new URI(URIUtility.createURI(s));

        if (new File(uri).exists()) {
            PropertyConfigurator.configure(uri.toURL());
            System.out.println("Using log4j configuration at: " + s);
        } else {
            System.out.println("Cannot find log properties file at " + s + " Using default log4j properties");
            PropertyConfigurator.configure(getClass().getResource("/log4j.properties"));
        }

        System.setProperty("activemq.base", rifidiHome + File.separator + "config");
    } catch (Throwable e) {
        e.printStackTrace();
    }

}

From source file:hu.dolphio.tprttapi.service.TrackingFlushServiceTpImpl.java

public TrackingFlushServiceTpImpl(String dateFrom, String dateTo) {
    this.dateFrom = dateFrom;
    this.dateTo = dateTo;

    targetHost = new HttpHost(propertyReader.getTpHost(), 80, "http");
    credsProvider = new BasicCredentialsProvider();
    Credentials credentials = new UsernamePasswordCredentials(propertyReader.getTpUserName(),
            propertyReader.getTpPassword());
    credsProvider.setCredentials(new AuthScope(targetHost.getHostName(), targetHost.getPort()), credentials);
    config = RequestConfig.custom().setSocketTimeout(propertyReader.getConnectionTimeout())
            .setConnectTimeout(propertyReader.getConnectionTimeout()).build();

    AuthCache authCache = new BasicAuthCache();

    BasicScheme basicAuth = new BasicScheme();
    authCache.put(targetHost, basicAuth);

    clientContext.setAuthCache(authCache);
}