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:net.ymate.framework.commons.HttpClientHelper.java

private CloseableHttpClient __doBuildHttpClient() throws KeyManagementException, NoSuchAlgorithmException {
    HttpClientBuilder _builder = HttpClientBuilder.create()
            .setDefaultRequestConfig(RequestConfig.custom().setConnectTimeout(__connectionTimeout)
                    .setSocketTimeout(__socketTimeout).setConnectionRequestTimeout(__requestTimeout).build());
    if (__socketFactory == null) {
        __socketFactory = new SSLConnectionSocketFactory(SSLContexts.createSystemDefault(),
                NoopHostnameVerifier.INSTANCE);
    }/*  ww  w  .  ja v a 2  s .  co  m*/
    return _builder.setSSLSocketFactory(__socketFactory).build();
}

From source file:com.intuit.karate.http.apache.ApacheHttpClient.java

@Override
public void configure(HttpConfig config) {
    clientBuilder = HttpClientBuilder.create();
    cookieStore = new BasicCookieStore();
    clientBuilder.setDefaultCookieStore(cookieStore);
    AtomicInteger counter = new AtomicInteger();
    clientBuilder.addInterceptorLast(new RequestLoggingInterceptor(counter));
    clientBuilder.addInterceptorLast(new ResponseLoggingInterceptor(counter));
    if (config.isSslEnabled()) {
        // System.setProperty("jsse.enableSNIExtension", "false");
        String sslAlgorithm = config.getSslAlgorithm();
        logger.info("ssl enabled, initializing generic trusted certificate / key-store with algorithm: {}",
                sslAlgorithm);/*from   w  ww.j a  v  a  2  s  .c  o  m*/
        SSLContext sslContext = HttpUtils.getSslContext(sslAlgorithm);
        SSLConnectionSocketFactory socketFactory = new LenientSslConnectionSocketFactory(sslContext,
                new NoopHostnameVerifier());
        clientBuilder.setSSLSocketFactory(socketFactory);
    }

    RequestConfig.Builder configBuilder = RequestConfig.custom().setConnectTimeout(config.getConnectTimeout())
            .setSocketTimeout(config.getReadTimeout());
    clientBuilder.setDefaultRequestConfig(configBuilder.build());
    if (config.getProxyUri() != null) {
        try {
            URI proxyUri = new URIBuilder(config.getProxyUri()).build();
            clientBuilder.setProxy(new HttpHost(proxyUri.getHost(), proxyUri.getPort(), proxyUri.getScheme()));
            if (config.getProxyUsername() != null && config.getProxyPassword() != null) {
                CredentialsProvider credsProvider = new BasicCredentialsProvider();
                credsProvider.setCredentials(new AuthScope(proxyUri.getHost(), proxyUri.getPort()),
                        new UsernamePasswordCredentials(config.getProxyUsername(), config.getProxyPassword()));
                clientBuilder.setDefaultCredentialsProvider(credsProvider);

            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}

From source file:net.shibboleth.idp.cas.authn.PkixProxyAuthenticator.java

@Override
protected int authenticateProxyCallback(final URI callbackUri) throws GeneralSecurityException {
    CloseableHttpClient httpClient = null;
    CloseableHttpResponse response = null;
    try {//from w ww  .  java 2s  . co  m
        httpClient = createHttpClient();
        log.debug("Attempting to connect to {}", callbackUri);
        final HttpGet request = new HttpGet(callbackUri);
        request.setConfig(RequestConfig.custom().setConnectTimeout(timeout).setSocketTimeout(timeout).build());
        response = httpClient.execute(request);
        return response.getStatusLine().getStatusCode();
    } catch (ClientProtocolException e) {
        throw new RuntimeException("HTTP protocol error", e);
    } catch (SSLException e) {
        if (e.getCause() instanceof CertificateException) {
            throw (CertificateException) e.getCause();
        }
        throw new GeneralSecurityException("SSL connection error", e);
    } catch (IOException e) {
        throw new RuntimeException("IO error", e);
    } finally {
        close(response);
        close(httpClient);
    }
}

From source file:mx.openpay.client.core.impl.DefaultHttpServiceClient.java

protected CloseableHttpClient initHttpClient(final boolean requirePoolManager, final int connectionTimeout,
        final int socketTimeout) {
    CloseableHttpClient httpClient;//from   www .  j ava2 s  . com
    HttpClientConnectionManager manager;

    SSLConnectionSocketFactory sslSocketFactory;
    SSLContext tlsContext;
    try {
        try {
            tlsContext = new SSLContextBuilder().useProtocol("TLSv1.2").build();
        } catch (GeneralSecurityException e) {
            log.warn("Could not force protocol TLSv1.2: {}", e.getMessage());
            tlsContext = new SSLContextBuilder().build();
        }
        sslSocketFactory = new SSLConnectionSocketFactory(tlsContext);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }

    if (requirePoolManager) {
        manager = new PoolingHttpClientConnectionManager(
                RegistryBuilder.<ConnectionSocketFactory>create().register("https", sslSocketFactory).build());
    } else {
        manager = new BasicHttpClientConnectionManager(
                RegistryBuilder.<ConnectionSocketFactory>create().register("https", sslSocketFactory).build());
    }

    this.requestConfig = RequestConfig.custom().setConnectTimeout(connectionTimeout)
            .setSocketTimeout(socketTimeout).build();
    ConnectionConfig connnectionConfig = ConnectionConfig.custom().setCharset(Charset.forName("UTF-8")).build();
    httpClient = HttpClientBuilder.create().setConnectionManager(manager)
            .setDefaultConnectionConfig(connnectionConfig).setDefaultRequestConfig(this.requestConfig).build();
    return httpClient;
}

From source file:com.ngdata.hbaseindexer.indexer.FusionPipelineClient.java

public FusionPipelineClient(String endpointUrl, String fusionUser, String fusionPass, String fusionRealm)
        throws MalformedURLException {

    this.fusionUser = fusionUser;
    this.fusionPass = fusionPass;
    this.fusionRealm = fusionRealm;

    String fusionLoginConf = System.getProperty(FusionKrb5HttpClientConfigurer.LOGIN_CONFIG_PROP);
    if (fusionLoginConf != null && !fusionLoginConf.isEmpty()) {
        httpClient = FusionKrb5HttpClientConfigurer.createClient(fusionUser);
        isKerberos = true;//from w  w w  . ja  v  a2  s . c om
    } else {
        globalConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.BEST_MATCH).build();
        cookieStore = new BasicCookieStore();

        // build the HttpClient to be used for all requests
        HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
        httpClientBuilder.setDefaultRequestConfig(globalConfig).setDefaultCookieStore(cookieStore);
        httpClientBuilder.setMaxConnPerRoute(100);
        httpClientBuilder.setMaxConnTotal(500);

        if (fusionUser != null && fusionRealm == null)
            httpClientBuilder.addInterceptorFirst(new PreEmptiveBasicAuthenticator(fusionUser, fusionPass));

        httpClient = httpClientBuilder.build();
    }

    originalEndpoints = Arrays.asList(endpointUrl.split(","));
    try {
        sessions = establishSessions(originalEndpoints, fusionUser, fusionPass, fusionRealm);
    } catch (Exception exc) {
        if (exc instanceof RuntimeException) {
            throw (RuntimeException) exc;
        } else {
            throw new RuntimeException(exc);
        }
    }

    random = new Random();
    jsonObjectMapper = new ObjectMapper();

    requestCounter = new AtomicInteger(0);
}

From source file:org.nextlets.erc.defaults.http.ERCHttpInvokerImpl.java

protected void addProxy(ERCConfiguration configuration, HttpRequestBase req) {
    if (configuration.getProxyUrl() != null && !configuration.getProxyUrl().isEmpty()) {
        log.debug("Proxy: {}", configuration.getProxyUrl());
        URI proxyUri;//from   w ww  .j  a  va  2  s .  c  o  m
        try {
            proxyUri = new URI(configuration.getProxyUrl());
        } catch (URISyntaxException ex) {
            throw new ERCClientException(ex);
        }
        HttpHost proxy = new HttpHost(proxyUri.getHost(), proxyUri.getPort(), proxyUri.getScheme());
        req.setConfig(RequestConfig.custom().setProxy(proxy).build());
    }

}

From source file:com.arangodb.http.HttpManager.java

public void init() {
    // socket factory for HTTP
    ConnectionSocketFactory plainsf = new PlainConnectionSocketFactory();

    // socket factory for HTTPS
    SSLConnectionSocketFactory sslsf = null;
    if (configure.getSslContext() != null) {
        sslsf = new SSLConnectionSocketFactory(configure.getSslContext());
    } else {/*  w  w w  . j  a va  2  s. c om*/
        sslsf = new SSLConnectionSocketFactory(SSLContexts.createSystemDefault());
    }

    // register socket factories
    Registry<ConnectionSocketFactory> r = RegistryBuilder.<ConnectionSocketFactory>create()
            .register("http", plainsf).register("https", sslsf).build();

    // ConnectionManager
    cm = new PoolingHttpClientConnectionManager(r);
    cm.setDefaultMaxPerRoute(configure.getMaxPerConnection());
    cm.setMaxTotal(configure.getMaxTotalConnection());

    Builder custom = RequestConfig.custom();

    // RequestConfig
    if (configure.getConnectionTimeout() >= 0) {
        custom.setConnectTimeout(configure.getConnectionTimeout());
    }
    if (configure.getTimeout() >= 0) {
        custom.setConnectionRequestTimeout(configure.getTimeout());
        custom.setSocketTimeout(configure.getTimeout());
    }
    custom.setStaleConnectionCheckEnabled(configure.isStaleConnectionCheck());

    RequestConfig requestConfig = custom.build();

    HttpClientBuilder builder = HttpClientBuilder.create().setDefaultRequestConfig(requestConfig);
    builder.setConnectionManager(cm);

    // KeepAlive Strategy
    ConnectionKeepAliveStrategy keepAliveStrategy = new ConnectionKeepAliveStrategy() {

        @Override
        public long getKeepAliveDuration(HttpResponse response, HttpContext context) {
            // Honor 'keep-alive' header
            HeaderElementIterator it = new BasicHeaderElementIterator(
                    response.headerIterator(HTTP.CONN_KEEP_ALIVE));
            while (it.hasNext()) {
                HeaderElement he = it.nextElement();
                String param = he.getName();
                String value = he.getValue();
                if (value != null && param.equalsIgnoreCase("timeout")) {
                    try {
                        return Long.parseLong(value) * 1000;
                    } catch (NumberFormatException ignore) {
                    }
                }
            }
            // otherwise keep alive for 30 seconds
            return 30 * 1000;
        }

    };
    builder.setKeepAliveStrategy(keepAliveStrategy);

    // Retry Handler
    builder.setRetryHandler(new DefaultHttpRequestRetryHandler(configure.getRetryCount(), false));

    // Proxy
    if (configure.getProxyHost() != null && configure.getProxyPort() != 0) {
        HttpHost proxy = new HttpHost(configure.getProxyHost(), configure.getProxyPort(), "http");

        DefaultProxyRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxy);
        builder.setRoutePlanner(routePlanner);
    }

    // Client
    client = builder.build();

    // Basic Auth
    // if (configure.getUser() != null && configure.getPassword() != null) {
    // AuthScope scope = AuthScope.ANY; // TODO
    // this.credentials = new
    // UsernamePasswordCredentials(configure.getUser(),
    // configure.getPassword());
    // client.getCredentialsProvider().setCredentials(scope, credentials);
    // }

}

From source file:fr.treeptik.cloudunit.utils.JSONClient.java

public DockerResponse sendPostToRegistryHost(URI uri, String body, String contentType)
        throws JSONClientException {

    if (logger.isDebugEnabled()) {
        logger.debug("Send a post request to : " + uri);
        logger.debug("Body content : " + body);
        logger.debug("Content type : " + contentType);
    }//from  www . j  ava  2 s . com

    RequestConfig config = RequestConfig.custom().setSocketTimeout(1000 * 60 * 50)
            .setConnectTimeout(1000 * 60 * 50).build();
    HttpPost httpPost = new HttpPost(uri);
    httpPost.setConfig(config);
    httpPost.addHeader("content-type", contentType);
    httpPost.addHeader("X-Registry-Auth", "123");
    HttpResponse response = null;
    StringWriter writer = new StringWriter();
    try {
        CloseableHttpClient httpclient = buildSecureHttpClient(false);
        httpPost.setEntity(new StringEntity(body));
        response = httpclient.execute(httpPost);
        IOUtils.copy(response.getEntity().getContent(), writer, "UTF-8");
    } catch (IOException e) {
        throw new JSONClientException("Error in sendPostToRegistryHost method due to : " + e.getMessage(), e);
    }

    if (logger.isDebugEnabled()) {
        logger.debug("Status code : " + response.getStatusLine().getStatusCode());
        logger.debug("Server response : " + writer.toString());
    }

    return new DockerResponse(response.getStatusLine().getStatusCode(), writer.toString());
}

From source file:com.vmware.vim25.ws.ApacheHttpClient.java

private InputStream post(String payload) {
    CloseableHttpClient httpclient;/*from  www .  j a v a  2s. co m*/
    RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(this.connectTimeout)
            .setSocketTimeout(this.readTimeout).build();
    if (trustAllSSL) {
        httpclient = HttpClients.custom().setSSLSocketFactory(ApacheTrustSelfSigned.trust()).build();

    } else {
        httpclient = HttpClients.createDefault();
    }
    HttpPost httpPost;
    StringEntity stringEntity;
    try {
        stringEntity = new StringEntity(payload);
        log.trace("Converted payload to String entity.");
    } catch (UnsupportedEncodingException e) {
        log.error("Failed to convert payload to StringEntity. Unsupported Encoding Exception caught. Payload: "
                + payload, e);
        return null;
    }
    try {
        httpPost = new HttpPost(this.baseUrl.toURI());
    } catch (URISyntaxException e) {
        log.error("Malformed URI sent: " + this.baseUrl.toString(), e);
        return null;
    }
    httpPost.setConfig(requestConfig);
    httpPost.setHeader(SoapAction.SOAP_ACTION_HEADER.toString(), soapAction);
    httpPost.setHeader("Content-Type", "text/xml; charset=utf-8");
    if (cookie != null) {
        log.trace("Setting Cookie.");
        httpPost.setHeader("Cookie", cookie);
    }
    httpPost.setEntity(stringEntity);
    try {
        CloseableHttpResponse response = httpclient.execute(httpPost);
        InputStream inputStream = response.getEntity().getContent();
        if (cookie == null) {

            Header[] headers = response.getAllHeaders();
            for (Header header : headers) {
                if (header.getName().equals("Set-Cookie")) {
                    cookie = header.getValue();
                    break;
                }
            }
        }
        return inputStream;
    } catch (IOException e) {
        log.error("", e);
    }
    return null;
}