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:org.sonatype.nexus.internal.httpclient.HttpClientManagerImpl.java

@Override
@Guarded(by = STARTED)/*from  www. j av a  2s . 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.nextdoor.bender.ipc.es.ElasticSearchTransportFactory.java

@Override
protected CloseableHttpClient getClient(boolean useSSL, String url, Map<String, String> stringHeaders,
        int socketTimeout) {
    HttpClientBuilder cb = super.getClientBuilder(useSSL, url, stringHeaders, socketTimeout);
    ElasticSearchTransportConfig config = (ElasticSearchTransportConfig) super.config;

    if (config.getAuthConfig() != null) {
        if (config.getAuthConfig() instanceof BasicHttpAuthConfig) {
            cb = addUserPassAuth(cb, (BasicHttpAuthConfig) config.getAuthConfig());
        } else if (config.getAuthConfig() instanceof UrlSigningAuthConfig) {
            cb = addSigningAuth(cb, (UrlSigningAuthConfig) config.getAuthConfig());
        }//from  ww  w  .ja  va2 s.  c  o  m
    }

    RequestConfig rc = RequestConfig.custom().setConnectTimeout(5000).setSocketTimeout(config.getTimeout())
            .build();
    cb.setDefaultRequestConfig(rc);

    return cb.build();
}

From source file:com.liferay.sync.engine.session.Session.java

public static HttpClientBuilder createHttpClientBuilder(boolean trustSelfSigned, int maxConnections) {

    HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();

    httpClientBuilder.disableAutomaticRetries();

    RequestConfig.Builder builder = RequestConfig.custom();

    builder.setConnectTimeout(PropsValues.SYNC_HTTP_CONNECTION_TIMEOUT);

    if (maxConnections == Integer.MAX_VALUE) {
        builder.setSocketTimeout(PropsValues.SYNC_HTTP_SOCKET_TIMEOUT * 2);
    } else {//w w w .  j av  a 2 s  . com
        builder.setSocketTimeout(PropsValues.SYNC_HTTP_SOCKET_TIMEOUT);
    }

    List<Header> headers = new ArrayList<>(2);

    Header syncBuildHeader = new BasicHeader("Sync-Build", String.valueOf(ReleaseInfo.getBuildNumber()));

    headers.add(syncBuildHeader);

    String syncDeviceType = null;

    if (OSDetector.isApple()) {
        syncDeviceType = "desktop-mac";
    } else if (OSDetector.isLinux()) {
        syncDeviceType = "desktop-linux";
    } else if (OSDetector.isWindows()) {
        syncDeviceType = "desktop-windows";
    }

    Header syncDeviceTypeHeader = new BasicHeader("Sync-Device", syncDeviceType);

    headers.add(syncDeviceTypeHeader);

    httpClientBuilder.setDefaultHeaders(headers);

    httpClientBuilder.setDefaultRequestConfig(builder.build());
    httpClientBuilder.setMaxConnPerRoute(maxConnections);
    httpClientBuilder.setMaxConnTotal(maxConnections);
    httpClientBuilder.setRedirectStrategy(new LaxRedirectStrategy());
    httpClientBuilder.setRoutePlanner(getHttpRoutePlanner());

    try {
        if (trustSelfSigned) {
            httpClientBuilder.setSSLSocketFactory(_getTrustingSSLSocketFactory());
        } else {
            httpClientBuilder.setSSLSocketFactory(_getDefaultSSLSocketFactory());
        }
    } catch (Exception e) {
        _logger.error(e.getMessage(), e);
    }

    return httpClientBuilder;
}

From source file:de.vanita5.twittnuker.util.net.TwidereHttpClientImpl.java

public TwidereHttpClientImpl(final Context context, final HttpClientConfiguration conf) {
    this.conf = conf;
    final HttpClientBuilder clientBuilder = HttpClients.custom();
    final LayeredConnectionSocketFactory factory = TwidereSSLSocketFactory.getSocketFactory(context,
            conf.isSSLErrorIgnored());/* ww w.  jav a2s.c  o  m*/
    clientBuilder.setSSLSocketFactory(factory);
    final RequestConfig.Builder requestConfigBuilder = RequestConfig.custom();
    requestConfigBuilder.setConnectionRequestTimeout(conf.getHttpConnectionTimeout());
    requestConfigBuilder.setConnectTimeout(conf.getHttpConnectionTimeout());
    requestConfigBuilder.setSocketTimeout(conf.getHttpReadTimeout());
    requestConfigBuilder.setRedirectsEnabled(false);
    clientBuilder.setDefaultRequestConfig(requestConfigBuilder.build());
    if (conf.isProxyConfigured()) {
        final HttpHost proxy = new HttpHost(conf.getHttpProxyHost(), conf.getHttpProxyPort());
        clientBuilder.setProxy(proxy);
        if (!TextUtils.isEmpty(conf.getHttpProxyUser())) {
            if (logger.isDebugEnabled()) {
                logger.debug("Proxy AuthUser: " + conf.getHttpProxyUser());
                logger.debug(
                        "Proxy AuthPassword: " + InternalStringUtil.maskString(conf.getHttpProxyPassword()));
            }
            final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
            credentialsProvider.setCredentials(new AuthScope(conf.getHttpProxyHost(), conf.getHttpProxyPort()),
                    new UsernamePasswordCredentials(conf.getHttpProxyUser(), conf.getHttpProxyPassword()));
            clientBuilder.setDefaultCredentialsProvider(credentialsProvider);
        }
    }
    client = clientBuilder.build();
}

From source file:com.delphix.delphix.DelphixEngine.java

public DelphixEngine(DelphixEngine engine) {
    this.engineAddress = engine.engineAddress;
    this.engineUsername = engine.engineUsername;
    this.enginePassword = engine.enginePassword;

    RequestConfig.Builder requestBuilder = RequestConfig.custom();
    requestBuilder = requestBuilder.setConnectTimeout(60 * 1000);
    requestBuilder = requestBuilder.setConnectionRequestTimeout(60 * 1000);
    requestBuilder = requestBuilder.setSocketTimeout(60 * 1000);

    HttpClientBuilder builder = HttpClientBuilder.create();
    builder.setDefaultRequestConfig(requestBuilder.build());
    client = builder.build();/*from ww  w .  ja v a 2  s .  c  o m*/
}

From source file:com.delphix.delphix.DelphixEngine.java

@DataBoundConstructor
public DelphixEngine(String engineAddress, String engineUsername, String enginePassword) {
    this.engineAddress = engineAddress;
    this.engineUsername = engineUsername;
    this.enginePassword = enginePassword;

    RequestConfig.Builder requestBuilder = RequestConfig.custom();
    requestBuilder = requestBuilder.setConnectTimeout(60 * 1000);
    requestBuilder = requestBuilder.setConnectionRequestTimeout(60 * 1000);
    requestBuilder = requestBuilder.setSocketTimeout(60 * 1000);

    HttpClientBuilder builder = HttpClientBuilder.create();
    builder.setDefaultRequestConfig(requestBuilder.build());
    client = builder.build();/* w ww.j av a  2s.com*/
}

From source file:net.sf.jasperreports.data.http.HttpDataService.java

protected CloseableHttpClient createHttpClient(Map<String, Object> parameters) {
    HttpClientBuilder clientBuilder = HttpClients.custom();

    // single connection
    BasicHttpClientConnectionManager connManager = new BasicHttpClientConnectionManager();
    clientBuilder.setConnectionManager(connManager);

    // ignore cookies for now
    RequestConfig requestConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.IGNORE_COOKIES).build();
    clientBuilder.setDefaultRequestConfig(requestConfig);

    setAuthentication(parameters, clientBuilder);

    CloseableHttpClient client = clientBuilder.build();
    return client;
}

From source file:eu.europa.ec.markt.dss.validation102853.https.CommonsDataLoader.java

protected synchronized HttpClient getHttpClient(final String url) throws DSSException {

    if (httpClient != null) {

        return httpClient;
    } else {/* w  ww  . j  a  va 2  s.  c  o m*/

        HttpClientBuilder httpClientBuilder = HttpClients.custom();

        httpClientBuilder = configCredentials(httpClientBuilder, url);

        final RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(timeoutSocket)
                .setConnectionRequestTimeout(timeoutConnection).build();
        httpClientBuilder = httpClientBuilder.setDefaultRequestConfig(requestConfig);
        httpClientBuilder.setConnectionManager(getConnectionManager());

        httpClient = httpClientBuilder.build();
        return httpClient;
    }
}