Example usage for org.apache.http.impl.client HttpClientBuilder setDefaultRequestConfig

List of usage examples for org.apache.http.impl.client HttpClientBuilder setDefaultRequestConfig

Introduction

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

Prototype

public final HttpClientBuilder setDefaultRequestConfig(final RequestConfig config) 

Source Link

Document

Assigns default RequestConfig instance which will be used for request execution if not explicitly set in the client execution context.

Usage

From source file:de.perdian.apps.dashboard.support.clients.JsonClient.java

public JsonClient(String username, String password, int timeout) {
    RequestConfig.Builder requestBuilder = RequestConfig.custom();
    requestBuilder.setConnectTimeout(timeout);
    requestBuilder.setSocketTimeout(timeout);
    HttpClientBuilder clientBuilder = HttpClientBuilder.create();
    clientBuilder.setDefaultRequestConfig(requestBuilder.build());
    this.setHttpClient(clientBuilder.build());
    this.setDefaultHeaders(new Properties());
    this.setUsername(username);
    this.setPassword(password);
}

From source file:org.apache.solr.client.solrj.impl.ExternalHttpClientTest.java

/**
 * The internal client created by HttpSolrClient is a SystemDefaultHttpClient
 * which takes care of merging request level params (such as timeout) with the
 * configured defaults.//w w  w .ja va 2 s  .com
 *
 * However, if an external HttpClient is passed to HttpSolrClient,
 * the logic in InternalHttpClient.executeMethod replaces the configured defaults
 * by request level params if they exist. That is why we must test a setting such
 * as timeout with an external client to assert that the defaults are indeed being
 * used
 *
 * See SOLR-6245 for more details
 */
@Test
public void testTimeoutWithExternalClient() throws Exception {

    HttpClientBuilder builder = HttpClientBuilder.create();
    RequestConfig config = RequestConfig.custom().setSocketTimeout(2000).build();
    builder.setDefaultRequestConfig(config);

    try (CloseableHttpClient httpClient = builder.build();
            HttpSolrClient solrClient = new HttpSolrClient(jetty.getBaseUrl().toString() + "/slow/foo",
                    httpClient)) {

        SolrQuery q = new SolrQuery("*:*");
        try {
            solrClient.query(q, SolrRequest.METHOD.GET);
            fail("No exception thrown.");
        } catch (SolrServerException e) {
            assertTrue(e.getMessage().contains("Timeout"));
        }
    }
}

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 {/* www  .  jav  a  2s .c  om*/
        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:org.sonatype.nexus.testsuite.NexusHttpsITSupport.java

/**
 * @return Client that can use preemptive auth and self-signed certificates
 *///w  w  w.ja va 2s .  co m
protected HttpClientBuilder clientBuilder() throws Exception {
    HttpClientBuilder builder = HttpClients.custom();
    builder.setDefaultRequestConfig(requestConfig());
    builder.setDefaultCredentialsProvider(credentialsProvider());
    builder.setSSLSocketFactory(sslSocketFactory());
    return builder;
}

From source file:org.fao.geonet.util.XslUtil.java

/**
 * Returns the HTTP code  or error message if error occurs during URL connection.
 *
 * @param url       The URL to ckeck./*from   www  .  jav a 2  s. c  o m*/
 * @param tryNumber the number of remaining tries.
 */
public static String getUrlStatus(String url, int tryNumber) {
    if (tryNumber < 1) {
        // protect against redirect loops
        return "ERR_TOO_MANY_REDIRECTS";
    }
    HttpHead head = new HttpHead(url);
    GeonetHttpRequestFactory requestFactory = ApplicationContextHolder.get()
            .getBean(GeonetHttpRequestFactory.class);
    ClientHttpResponse response = null;
    try {
        response = requestFactory.execute(head, new Function<HttpClientBuilder, Void>() {
            @Nullable
            @Override
            public Void apply(@Nullable HttpClientBuilder originalConfig) {
                RequestConfig.Builder config = RequestConfig.custom().setConnectTimeout(1000)
                        .setConnectionRequestTimeout(3000).setSocketTimeout(5000);
                RequestConfig requestConfig = config.build();
                originalConfig.setDefaultRequestConfig(requestConfig);

                return null;
            }
        });
        //response = requestFactory.execute(head);
        if (response.getRawStatusCode() == HttpStatus.SC_BAD_REQUEST
                || response.getRawStatusCode() == HttpStatus.SC_METHOD_NOT_ALLOWED
                || response.getRawStatusCode() == HttpStatus.SC_INTERNAL_SERVER_ERROR) {
            // the website doesn't support HEAD requests. Need to do a GET...
            response.close();
            HttpGet get = new HttpGet(url);
            response = requestFactory.execute(get);
        }

        if (response.getStatusCode().is3xxRedirection() && response.getHeaders().containsKey("Location")) {
            // follow the redirects
            return getUrlStatus(response.getHeaders().getFirst("Location"), tryNumber - 1);
        }

        return String.valueOf(response.getRawStatusCode());
    } catch (IOException e) {
        Log.error(Geonet.GEONETWORK, "IOException validating  " + url + " URL. " + e.getMessage(), e);
        return e.getMessage();
    } finally {
        if (response != null) {
            response.close();
        }
    }
}

From source file:org.scassandra.http.client.CurrentClient.java

private CurrentClient(String host, int port, int socketTimeout) {
    RequestConfig.Builder requestBuilder = RequestConfig.custom();
    requestBuilder = requestBuilder.setConnectTimeout(socketTimeout);
    requestBuilder = requestBuilder.setConnectionRequestTimeout(socketTimeout);
    requestBuilder = requestBuilder.setSocketTimeout(socketTimeout);
    HttpClientBuilder builder = HttpClientBuilder.create();
    builder.setDefaultRequestConfig(requestBuilder.build());
    httpClient = builder.build();/*from w  w w  .ja va 2 s.c  o  m*/
    this.currentUrl = "http://" + host + ":" + port + "/current";
    this.connectionsUrl = this.currentUrl + "/connections";
    this.listenerUrl = this.currentUrl + "/listener";
}

From source file:co.tuzza.clicksend4j.http.HttpClientUtils.java

public HttpClient getHttpClient() {

    HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
    httpClientBuilder.setUserAgent("ClickSend4J 0.0.1");
    httpClientBuilder.setConnectionManager(clientConnectionManager);
    httpClientBuilder.setDefaultRequestConfig(buildRequestConfig());

    return httpClientBuilder.build();

}

From source file:net.yacy.cora.protocol.http.HTTPClient.java

private static HttpClientBuilder initClientBuilder() {
    final HttpClientBuilder builder = HttpClientBuilder.create();

    builder.setConnectionManager(CONNECTION_MANAGER);
    builder.setDefaultRequestConfig(dfltReqConf);

    // UserAgent/*from   ww w.j a va 2s. co m*/
    builder.setUserAgent(ClientIdentification.yacyInternetCrawlerAgent.userAgent);

    // remove retries; we expect connections to fail; therefore we should not retry
    //builder.disableAutomaticRetries();
    // disable the cookiestore, cause this may cause segfaults and is not needed
    builder.setDefaultCookieStore(null);
    builder.disableCookieManagement();

    // add custom keep alive strategy
    builder.setKeepAliveStrategy(customKeepAliveStrategy());

    // ask for gzip
    builder.addInterceptorLast(new GzipRequestInterceptor());
    // uncompress gzip
    builder.addInterceptorLast(new GzipResponseInterceptor());
    // Proxy
    builder.setRoutePlanner(ProxySettings.RoutePlanner);
    builder.setDefaultCredentialsProvider(ProxySettings.CredsProvider);

    return builder;
}

From source file:com.crosstreelabs.cognitio.gumshoe.transport.HttpTransport.java

private void buildHttpClient() {
    requestConfig = RequestConfig.custom().setExpectContinueEnabled(false).setCookieSpec(CookieSpecs.DEFAULT)
            .setRedirectsEnabled(false).setSocketTimeout(5000).setConnectTimeout(5000)
            .setConnectionRequestTimeout(5000).setStaleConnectionCheckEnabled(true).build();

    RegistryBuilder<ConnectionSocketFactory> connRegistryBuilder = RegistryBuilder.create();
    connRegistryBuilder.register("http", PlainConnectionSocketFactory.INSTANCE);
    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/*w  w  w .  j a v a  2s.c om*/
            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 (KeyManagementException | KeyStoreException | NoSuchAlgorithmException 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(5);
    connectionManager.setDefaultMaxPerRoute(5);

    HttpClientBuilder clientBuilder = HttpClientBuilder.create();
    clientBuilder.setDefaultRequestConfig(requestConfig);
    clientBuilder.setConnectionManager(connectionManager);
    clientBuilder.setUserAgent("Cognitio");

    httpClient = clientBuilder.build();
}