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

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

Introduction

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

Prototype

public final HttpClientBuilder setDefaultConnectionConfig(final ConnectionConfig config) 

Source Link

Document

Assigns default ConnectionConfig .

Usage

From source file:org.sonatype.nexus.internal.httpclient.HttpClientManagerImpl.java

@Override
@Guarded(by = STARTED)//from   ww w  .  ja v  a2 s. c o  m
public HttpClientBuilder prepare(@Nullable final Customizer customizer) {
    final HttpClientPlan plan = httpClientPlan();

    // attach connection manager early, so customizer has chance to replace it if needed
    plan.getClient().setConnectionManager(sharedConnectionManager);

    // apply defaults
    defaultsCustomizer.customize(plan);

    // apply globals
    new ConfigurationCustomizer(getConfigurationInternal()).customize(plan);

    // apply instance customization
    if (customizer != null) {
        customizer.customize(plan);
    }

    // apply plan to builder
    HttpClientBuilder builder = plan.getClient();
    // User agent must be set here to apply to all apache http requests, including over proxies
    String userAgent = plan.getUserAgent();
    if (userAgent != null) {
        setUserAgent(builder, userAgent);
    }
    builder.setDefaultConnectionConfig(plan.getConnection().build());
    builder.setDefaultSocketConfig(plan.getSocket().build());
    builder.setDefaultRequestConfig(plan.getRequest().build());
    builder.setDefaultCredentialsProvider(plan.getCredentials());

    builder.addInterceptorFirst((HttpRequest request, HttpContext context) -> {
        // add custom http-context attributes
        for (Entry<String, Object> entry : plan.getAttributes().entrySet()) {
            // only set context attribute if not already set, to allow per request overrides
            if (context.getAttribute(entry.getKey()) == null) {
                context.setAttribute(entry.getKey(), entry.getValue());
            }
        }

        // add custom http-request headers
        for (Entry<String, String> entry : plan.getHeaders().entrySet()) {
            request.addHeader(entry.getKey(), entry.getValue());
        }
    });
    builder.addInterceptorLast((HttpRequest httpRequest, HttpContext httpContext) -> {
        if (outboundLog.isDebugEnabled()) {
            httpContext.setAttribute(CTX_REQ_STOPWATCH, Stopwatch.createStarted());
            httpContext.setAttribute(CTX_REQ_URI, getRequestURI(httpContext));
            outboundLog.debug("{} > {}", httpContext.getAttribute(CTX_REQ_URI), httpRequest.getRequestLine());
        }
    });
    builder.addInterceptorLast((HttpResponse httpResponse, HttpContext httpContext) -> {
        Stopwatch stopwatch = (Stopwatch) httpContext.getAttribute(CTX_REQ_STOPWATCH);
        if (stopwatch != null) {
            outboundLog.debug("{} < {} @ {}", httpContext.getAttribute(CTX_REQ_URI),
                    httpResponse.getStatusLine(), stopwatch);
        }
    });

    return builder;
}

From source file:com.baidubce.http.BceHttpClient.java

/**
 * Create http client based on connection manager.
 *
 * @param connectionManager The connection manager setting http client.
 * @return Http client based on connection manager.
 *///from ww  w.j  a  v  a 2 s .  co m
private CloseableHttpClient createHttpClient(HttpClientConnectionManager connectionManager) {
    HttpClientBuilder builder = HttpClients.custom().setConnectionManager(connectionManager)
            .disableAutomaticRetries();

    int socketBufferSizeInBytes = this.config.getSocketBufferSizeInBytes();
    if (socketBufferSizeInBytes > 0) {
        builder.setDefaultConnectionConfig(
                ConnectionConfig.custom().setBufferSize(socketBufferSizeInBytes).build());
    }

    return builder.build();
}

From source file:com.gs.tools.doc.extractor.core.DownloadManager.java

private DownloadManager() {
    logger.info("Init DownloadManager");
    cookieStore = new BasicCookieStore();
    HttpClientBuilder clientBuilder = HttpClientBuilder.create();
    clientBuilder.setDefaultCookieStore(cookieStore);

    Collection<Header> headers = new ArrayList<Header>();
    headers.add(new BasicHeader("Accept",
            "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8"));
    headers.add(new BasicHeader("User-Agent",
            "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.57 Safari/537.36"));
    headers.add(new BasicHeader("Accept-Encoding", "gzip,deflate,sdch"));
    headers.add(new BasicHeader("Accept-Language", "en-US,en;q=0.8"));
    //        headers.add(new BasicHeader("Accept-Encoding", 
    //                "gzip,deflate,sdch"));
    clientBuilder.setDefaultHeaders(headers);

    ConnectionConfig.Builder connectionConfigBuilder = ConnectionConfig.custom();
    connectionConfigBuilder.setBufferSize(10485760);
    clientBuilder.setDefaultConnectionConfig(connectionConfigBuilder.build());

    SocketConfig.Builder socketConfigBuilder = SocketConfig.custom();
    socketConfigBuilder.setSoKeepAlive(true);
    socketConfigBuilder.setSoTimeout(3000000);
    clientBuilder.setDefaultSocketConfig(socketConfigBuilder.build());
    logger.info("Create HTTP Client");
    httpClient = clientBuilder.build();/*  w  w w  . j  a  v a2s  .  co m*/

}

From source file:com.norconex.collector.http.client.impl.GenericHttpClientFactory.java

@Override
public HttpClient createHTTPClient(String userAgent) {
    HttpClientBuilder builder = HttpClientBuilder.create();
    builder.setSslcontext(createSSLContext());
    builder.setSchemePortResolver(createSchemePortResolver());
    builder.setDefaultRequestConfig(createRequestConfig());
    builder.setProxy(createProxy());//from   w w w.j a va 2 s .  co m
    builder.setDefaultCredentialsProvider(createCredentialsProvider());
    builder.setDefaultConnectionConfig(createConnectionConfig());
    builder.setUserAgent(userAgent);
    builder.setMaxConnTotal(maxConnections);
    //builder.setMaxConnPerRoute(maxConnPerRoute)
    buildCustomHttpClient(builder);

    //TODO Put in place a more permanent solution to the following
    //Fix GitHub #17 start
    RedirectStrategy strategy = createRedirectStrategy();
    if (strategy == null) {
        strategy = LaxRedirectStrategy.INSTANCE;
    }
    builder.setRedirectStrategy(new TargetURLRedirectStrategy(strategy));
    //Fix end

    HttpClient httpClient = builder.build();
    if (AUTH_METHOD_FORM.equalsIgnoreCase(authMethod)) {
        authenticateUsingForm(httpClient);
    }
    return httpClient;
}

From source file:org.attribyte.api.http.impl.commons.Commons4Client.java

private void initFromOptions(final ClientOptions options) {

    if (options != ClientOptions.IMPLEMENTATION_DEFAULT) {

        HttpClientBuilder builder = HttpClients.custom();
        builder.setMaxConnTotal(options.maxConnectionsTotal);
        builder.setMaxConnPerRoute(options.maxConnectionsPerDestination);
        builder.setUserAgent(options.userAgent);
        if (options.proxyHost != null) {
            builder.setProxy(new HttpHost(options.proxyHost, options.proxyPort));
        }/*from w w  w .ja va  2s.  c om*/

        this.defaultRequestConfig = RequestConfig.custom().setConnectTimeout(options.connectionTimeoutMillis)
                .setConnectionRequestTimeout(options.requestTimeoutMillis)
                .setRedirectsEnabled(RequestOptions.DEFAULT_FOLLOW_REDIRECTS)
                .setMaxRedirects(RequestOptions.DEFAULT_FOLLOW_REDIRECTS ? 5 : 0)
                .setAuthenticationEnabled(false).setCircularRedirectsAllowed(false)
                .setSocketTimeout(options.socketTimeoutMillis).build();
        builder.setDefaultRequestConfig(defaultRequestConfig);

        ConnectionConfig connectionConfig = ConnectionConfig.custom()
                .setBufferSize(
                        options.requestBufferSize > options.responseBufferSize ? options.requestBufferSize
                                : options.responseBufferSize)
                .build();
        builder.setDefaultConnectionConfig(connectionConfig);

        this.httpClient = builder.build();
    } else {
        this.defaultRequestConfig = RequestConfig.DEFAULT;
        this.httpClient = HttpClients.createDefault();
    }
}