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.wareninja.opensource.dizlink.utils.MyWebClient.java

protected void initBase() {
    httpClient = HttpClients.createDefault();
    httpRequestConfig = RequestConfig.custom().setSocketTimeout(TIMEOUT).setConnectTimeout(TIMEOUT).build();

    localContext = new BasicHttpContext();
}

From source file:org.springframework.cloud.netflix.ribbon.apache.RetryableRibbonLoadBalancingHttpClient.java

@Override
public RibbonApacheHttpResponse execute(final RibbonApacheHttpRequest request,
        final IClientConfig configOverride) throws Exception {
    final RequestConfig.Builder builder = RequestConfig.custom();
    IClientConfig config = configOverride != null ? configOverride : this.config;
    builder.setConnectTimeout(config.get(CommonClientConfigKey.ConnectTimeout, this.connectTimeout));
    builder.setSocketTimeout(config.get(CommonClientConfigKey.ReadTimeout, this.readTimeout));
    builder.setRedirectsEnabled(config.get(CommonClientConfigKey.FollowRedirects, this.followRedirects));

    final RequestConfig requestConfig = builder.build();
    final LoadBalancedRetryPolicy retryPolicy = loadBalancedRetryPolicyFactory.create(this.getClientName(),
            this);
    RetryCallback retryCallback = new RetryCallback() {
        @Override/* w w  w  .jav  a  2  s . c o  m*/
        public RibbonApacheHttpResponse doWithRetry(RetryContext context) throws Exception {
            //on retries the policy will choose the server and set it in the context
            //extract the server and update the request being made
            RibbonApacheHttpRequest newRequest = request;
            if (context instanceof LoadBalancedRetryContext) {
                ServiceInstance service = ((LoadBalancedRetryContext) context).getServiceInstance();
                if (service != null) {
                    //Reconstruct the request URI using the host and port set in the retry context
                    newRequest = newRequest
                            .withNewUri(new URI(service.getUri().getScheme(), newRequest.getURI().getUserInfo(),
                                    service.getHost(), service.getPort(), newRequest.getURI().getPath(),
                                    newRequest.getURI().getQuery(), newRequest.getURI().getFragment()));
                }
            }
            if (isSecure(configOverride)) {
                final URI secureUri = UriComponentsBuilder.fromUri(newRequest.getUri()).scheme("https").build()
                        .toUri();
                newRequest = newRequest.withNewUri(secureUri);
            }
            HttpUriRequest httpUriRequest = newRequest.toRequest(requestConfig);
            final HttpResponse httpResponse = RetryableRibbonLoadBalancingHttpClient.this.delegate
                    .execute(httpUriRequest);
            if (retryPolicy.retryableStatusCode(httpResponse.getStatusLine().getStatusCode())) {
                throw new RetryableStatusCodeException(RetryableRibbonLoadBalancingHttpClient.this.clientName,
                        httpResponse.getStatusLine().getStatusCode());
            }
            return new RibbonApacheHttpResponse(httpResponse, httpUriRequest.getURI());
        }
    };
    return this.executeWithRetry(request, retryPolicy, retryCallback);
}

From source file:com.byteengine.client.Client.java

public void setProxySettings(String proxyHost, int proxyPort, String proxyUsername, String proxyPass) {
    HttpHost proxy = new HttpHost(proxyHost, proxyPort);

    proxyConfig = RequestConfig.custom().setProxy(proxy).build();

    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    AuthScope authScope = new AuthScope(proxyHost, proxyPort);
    UsernamePasswordCredentials creds = new UsernamePasswordCredentials(proxyUsername, proxyPass);
    credsProvider.setCredentials(authScope, creds);

    httpClient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build();
}

From source file:com.ibm.stocator.fs.swift.http.SwiftConnectionManager.java

/**
 * Default constructor//from  w  ww  . ja  v  a  2  s. co m
 * @param connectionConfigurationT connection conf
 */
public SwiftConnectionManager(ConnectionConfiguration connectionConfigurationT) {
    connectionConfiguration = connectionConfigurationT;
    connectionPool = new PoolingHttpClientConnectionManager();
    LOG.trace("SwiftConnectionManager: setDefaultMaxPerRoute {}", connectionConfiguration.getMaxPerRoute());
    connectionPool.setDefaultMaxPerRoute(connectionConfiguration.getMaxPerRoute());
    LOG.trace("SwiftConnectionManager: getMaxTotal {}", connectionConfiguration.getMaxTotal());
    connectionPool.setMaxTotal(connectionConfiguration.getMaxTotal());
    LOG.trace("Generate SocketConfig with soTimeout of {}", connectionConfiguration.getSoTimeout());
    SocketConfig socketConfig = SocketConfig.custom().setSoKeepAlive(false)
            .setSoTimeout(connectionConfiguration.getSoTimeout()).build();
    connectionPool.setDefaultSocketConfig(socketConfig);
    rConfig = RequestConfig.custom().setExpectContinueEnabled(true)
            .setConnectTimeout(connectionConfiguration.getReqConnectTimeout())
            .setConnectionRequestTimeout(connectionConfiguration.getReqConnectionRequestTimeout())
            .setSocketTimeout(connectionConfiguration.getReqSocketTimeout()).build();
}

From source file:org.opensextant.xtext.collectors.sharepoint.SharepointClient.java

/**
 * Sharepoint requires NTLM. This client requires a non-null user/passwd/domain.
 * /*from w ww . j  a v a  2s.c  om*/
 */
@Override
public HttpClient getClient() {

    if (currentConn != null) {
        return currentConn;
    }

    HttpClientBuilder clientHelper = HttpClientBuilder.create();

    if (proxyHost != null) {
        clientHelper.setProxy(proxyHost);
    }

    RequestConfig globalConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.BROWSER_COMPATIBILITY)
            .build();

    CredentialsProvider creds = new BasicCredentialsProvider();
    creds.setCredentials(AuthScope.ANY, new NTCredentials(user, passwd, server, domain));
    clientHelper.setDefaultCredentialsProvider(creds);
    HttpClient httpClient = clientHelper.setDefaultRequestConfig(globalConfig).build();

    return httpClient;

}

From source file:com.stratio.qa.utils.GosecSSOUtils.java

/**
 * This method provide dcos and sso token to be used to generate client cookie
 * @return cookieToken list of token generated
 * @throws Exception exception/*from  w  w  w.  jav a2s.c  o  m*/
 */
public HashMap<String, String> ssoTokenGenerator() throws Exception {
    String protocol = "https://";
    HashMap<String, String> cookieToken = new HashMap<>();

    SSLContext sslContext = SSLContext.getInstance("SSL");
    // set up a TrustManager that trusts everything
    sslContext.init(null, ALL_TRUSTING_TRUST_MANAGER, new SecureRandom());
    HttpClientContext context = HttpClientContext.create();
    HttpGet httpGet = new HttpGet(protocol + ssoHost + "/login");
    HttpClient client = HttpClientBuilder.create().setSslcontext(sslContext)
            .setRedirectStrategy(new LaxRedirectStrategy())
            .setDefaultRequestConfig(RequestConfig.custom().setCircularRedirectsAllowed(true).build()).build();
    try {
        HttpResponse firstResponse = client.execute(httpGet, context);

        logger.debug(firstResponse.getStatusLine().toString());
        Document doc = Jsoup.parse(getStringFromIS(firstResponse.getEntity().getContent()));
        Elements code = doc.select("[name=lt]");
        String loginCode = code.attr("value");
        String executionCode = doc.select("[name=execution]").attr("value");
        for (Header oneHeader : firstResponse.getAllHeaders()) {
            logger.debug(oneHeader.getName() + ":" + oneHeader.getValue());
        }

        URI redirect = context.getRedirectLocations().get(context.getRedirectLocations().size() - 1);

        List<NameValuePair> params = new ArrayList<>();
        params.add(new BasicNameValuePair("_eventId", "submit"));
        params.add(new BasicNameValuePair("submit", "LOGIN"));
        params.add(new BasicNameValuePair("username", userName));
        params.add(new BasicNameValuePair("password", passWord));
        params.add(new BasicNameValuePair("lt", loginCode));
        params.add(new BasicNameValuePair("execution", executionCode));
        HttpPost httpPost = new HttpPost(redirect);
        httpPost.setEntity(new UrlEncodedFormEntity(params));
        HttpResponse secondResponse = client.execute(httpPost, context);

        for (Header oneHeader : secondResponse.getAllHeaders()) {
            logger.debug(oneHeader.getName() + ":" + oneHeader.getValue());
        }

        HttpGet managementGet = new HttpGet(protocol + ssoHost + managementHost);
        client.execute(managementGet, context);

        for (Cookie oneCookie : context.getCookieStore().getCookies()) {
            logger.debug(oneCookie.getName() + ":" + oneCookie.getValue());
            cookieToken.put(oneCookie.getName(), oneCookie.getValue());
        }

    } catch (Exception e) {
        e.getStackTrace();
    }
    return cookieToken;
}

From source file:com.microsoft.applicationinsights.internal.channel.common.ApacheSender43.java

@Override
public void enhanceRequest(HttpPost request) {
    RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(REQUEST_TIMEOUT_IN_MILLIS)
            .setSocketTimeout(REQUEST_TIMEOUT_IN_MILLIS).setConnectTimeout(REQUEST_TIMEOUT_IN_MILLIS)
            .setSocketTimeout(REQUEST_TIMEOUT_IN_MILLIS).build();

    request.setConfig(requestConfig);/*from   w  w  w  .  ja  v  a2s . c o m*/
}

From source file:com.opentable.jaxrs.JaxRsClientFactoryImpl.java

private void configureHttpEngine(String clientName, ResteasyClientBuilder clientBuilder,
        JaxRsClientConfig config) {/*from   w  w w. j a  v  a  2  s.c  o  m*/
    final HttpClientBuilder builder = HttpClientBuilder.create();
    if (config.isEtcdHacksEnabled()) {
        builder.setRedirectStrategy(new ExtraLaxRedirectStrategy())
                .addInterceptorFirst(new SwallowHeaderInterceptor(HttpHeaders.CONTENT_LENGTH));
    }
    final MonitoredPoolingHttpClientConnectionManager connectionManager = new MonitoredPoolingHttpClientConnectionManager(
            clientName);

    connectionManager.setCheckoutWarnTime(Duration.ofMillis(config.connectionPoolWarnTime().getMillis()));
    connectionManager.setMaxTotal(config.connectionPoolSize());
    connectionManager.setDefaultMaxPerRoute(config.httpClientDefaultMaxPerRoute());

    final HttpClient client = builder
            .setDefaultSocketConfig(
                    SocketConfig.custom().setSoTimeout((int) config.socketTimeout().getMillis()).build())
            .setDefaultRequestConfig(customRequestConfig(config, RequestConfig.custom()))
            .setConnectionManager(connectionManager).build();
    final ApacheHttpClient4Engine engine = new HackedApacheHttpClient4Engine(config, client);
    clientBuilder.httpEngine(engine);
}

From source file:org.glassfish.jersey.apache.connector.DisableContentEncodingTest.java

@Test
public void testDisabledByRequestConfig() {
    ClientConfig cc = new ClientConfig(GZipEncoder.class);
    final RequestConfig requestConfig = RequestConfig.custom().setContentCompressionEnabled(false).build();
    cc.property(ApacheClientProperties.REQUEST_CONFIG, requestConfig);
    cc.connectorProvider(new ApacheConnectorProvider());
    Client client = ClientBuilder.newClient(cc);
    WebTarget r = client.target(getBaseUri());

    String enc = r.request().get().readEntity(String.class);
    assertEquals("", enc);
}

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));
        }//w  w w .j a  va  2s  .co  m

        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();
    }
}