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:com.adobe.acs.commons.http.impl.HttpClientFactoryImpl.java

@Activate
protected void activate(Map<String, Object> config) throws Exception {
    boolean useSSL = PropertiesUtil.toBoolean(config.get(PROP_USE_SSL), DEFAULT_USE_SSL);

    String scheme = useSSL ? "https" : "http";
    String hostname = PropertiesUtil.toString(config.get(PROP_HOST_DOMAIN), null);
    int port = PropertiesUtil.toInteger(config.get(PROP_GATEWAY_PORT), 0);

    if (hostname == null || port == 0) {
        throw new IllegalArgumentException("Configuration not valid. Both host and port must be provided.");
    }//from  www  .  jav  a2 s .  c om

    baseUrl = String.format("%s://%s:%s", scheme, hostname, port);

    int connectTimeout = PropertiesUtil.toInteger(config.get(PROP_CONNECT_TIMEOUT), DEFAULT_CONNECT_TIMEOUT);
    int soTimeout = PropertiesUtil.toInteger(config.get(PROP_SO_TIMEOUT), DEFAULT_SOCKET_TIMEOUT);

    HttpClientBuilder builder = httpClientBuilderFactory.newBuilder();

    RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(connectTimeout)
            .setSocketTimeout(soTimeout).build();
    builder.setDefaultRequestConfig(requestConfig);

    boolean disableCertCheck = PropertiesUtil.toBoolean(config.get(PROP_DISABLE_CERT_CHECK),
            DEFAULT_DISABLE_CERT_CHECK);

    if (useSSL && disableCertCheck) {
        SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
            public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
                return true;
            }
        }).build();
        builder.setHostnameVerifier(new AllowAllHostnameVerifier()).setSslcontext(sslContext);
    }
    httpClient = builder.build();
    executor = Executor.newInstance(httpClient);

    String username = PropertiesUtil.toString(config.get(PROP_USERNAME), null);
    String password = PropertiesUtil.toString(config.get(PROP_PASSWORD), null);
    if (username != null && password != null) {
        HttpHost httpHost = new HttpHost(hostname, port, useSSL ? "https" : "http");
        executor.auth(httpHost, username, password).authPreemptive(httpHost);
    }
}

From source file:info.bonjean.beluga.connection.BelugaHTTPClient.java

private BelugaHTTPClient() {
    BelugaConfiguration configuration = BelugaConfiguration.getInstance();
    HttpClientBuilder clientBuilder = HttpClients.custom();

    // timeout//from www.j a  v a  2  s. com
    RequestConfig config = RequestConfig.custom().setConnectTimeout(TIMEOUT).setSocketTimeout(TIMEOUT)
            .setConnectionRequestTimeout(TIMEOUT).build();
    clientBuilder.setDefaultRequestConfig(config);

    switch (configuration.getConnectionType()) {
    case PROXY_DNS:
        Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
                .register("http", PlainConnectionSocketFactory.getSocketFactory())
                .register("https", SSLConnectionSocketFactory.getSocketFactory()).build();
        BelugaDNSResolver dnsOverrider = new BelugaDNSResolver(DNSProxy.PROXY_DNS);
        connectionManager = new PoolingHttpClientConnectionManager(registry, dnsOverrider);
        break;
    case HTTP_PROXY:
        HttpHost proxy = new HttpHost(configuration.getProxyHost(), configuration.getProxyPort(), "http");
        clientBuilder.setProxy(proxy);
        break;
    default:
    }

    // limit the pool size
    connectionManager.setDefaultMaxPerRoute(2);

    // add interceptor, currently for debugging only
    clientBuilder.addInterceptorFirst(new HttpResponseInterceptor() {
        @Override
        public void process(HttpResponse response, HttpContext context) throws HttpException, IOException {
            HttpInetConnection connection = (HttpInetConnection) context
                    .getAttribute(HttpCoreContext.HTTP_CONNECTION);
            log.debug("Remote address: " + connection.getRemoteAddress());
            // TODO: reimplement blacklisting for DNS proxy by maintaining a
            // map [DNS IP,RESOLVED IP] in the DNS resolver for reverse
            // lookup
        }
    });

    // finally create the HTTP client
    clientBuilder.setConnectionManager(connectionManager);
    httpClient = clientBuilder.build();
}

From source file:org.hupo.psi.mi.psicquic.ws.SolrBasedPsicquicRestService.java

protected HttpClient createHttpClient() {
    PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
    cm.setMaxTotal(SolrBasedPsicquicService.maxTotalConnections);
    cm.setDefaultMaxPerRoute(SolrBasedPsicquicService.defaultMaxConnectionsPerHost);

    RequestConfig.Builder requestBuilder = RequestConfig.custom();
    requestBuilder = requestBuilder.setConnectTimeout(SolrBasedPsicquicService.connectionTimeOut);
    requestBuilder = requestBuilder.setSocketTimeout(SolrBasedPsicquicService.soTimeOut);

    HttpClientBuilder builder = HttpClientBuilder.create();
    builder.setDefaultRequestConfig(requestBuilder.build());
    builder.setConnectionManager(cm);// ww  w  . j a  va  2 s. co  m

    return builder.build();
}

From source file:org.apache.commons.jcs.auxiliary.remote.http.client.AbstractHttpClient.java

/**
 * Configures the http client./*from  w  w  w  . j a  v a 2s  .c om*/
 *
 * @param builder client builder to configure
 */
protected void configureClient(HttpClientBuilder builder) {
    if (getRemoteHttpCacheAttributes().getMaxConnectionsPerHost() > 0) {
        builder.setMaxConnTotal(getRemoteHttpCacheAttributes().getMaxConnectionsPerHost());
        builder.setMaxConnPerRoute(getRemoteHttpCacheAttributes().getMaxConnectionsPerHost());
    }

    builder.setDefaultRequestConfig(RequestConfig.custom()
            .setConnectTimeout(getRemoteHttpCacheAttributes().getConnectionTimeoutMillis())
            .setSocketTimeout(getRemoteHttpCacheAttributes().getSocketTimeoutMillis())
            // By default we instruct HttpClient to ignore cookies.
            .setCookieSpec(CookieSpecs.IGNORE_COOKIES).build());
}

From source file:org.asqatasun.util.http.HttpRequestHandler.java

private CloseableHttpClient getHttpClient(String url) {
    RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(socketTimeout)
            .setConnectTimeout(connectionTimeout).build();
    HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
    httpClientBuilder.setDefaultRequestConfig(requestConfig);
    httpClientBuilder.setConnectionManager(new PoolingHttpClientConnectionManager());
    httpClientBuilder.setUserAgent(ASQATASUN_USER_AGENT);
    if (isProxySet(url)) {
        LOGGER.debug(("Set proxy with " + proxyHost + " and " + proxyPort));
        httpClientBuilder.setProxy(new HttpHost(proxyHost, Integer.valueOf(proxyPort)));
        if (isProxyCredentialSet()) {
            CredentialsProvider credsProvider = new BasicCredentialsProvider();
            credsProvider.setCredentials(new AuthScope(proxyHost, Integer.valueOf(proxyPort)),
                    new UsernamePasswordCredentials(proxyUser, proxyPassword));
            httpClientBuilder.setDefaultCredentialsProvider(credsProvider);
            LOGGER.debug(("Set proxy credentials " + proxyHost + " and " + proxyPort + " and " + proxyUser
                    + " and " + proxyPassword));
        }/*from www .j  a v  a 2s.c  om*/
    }
    return httpClientBuilder.build();
}

From source file:org.openestate.is24.restapi.hc43.HttpComponents43Client.java

/**
 * Use a default {@link HttpClient} for HTTP traffic.
 *
 * @param timeout/*ww w.j  a v  a  2s. c  om*/
 * timeout for HTTP communication (in milliseconds)
 */
public void setDefaultHttpClient(int timeout) {
    if (timeout < 0)
        timeout = 0;
    //HttpParams params = new BasicHttpParams();
    //HttpProtocolParams.setVersion( params, HttpVersion.HTTP_1_1 );
    //HttpProtocolParams.setContentCharset( params, getEncoding() );
    //HttpProtocolParams.setUseExpectContinue( params, true );
    //HttpConnectionParams.setConnectionTimeout( params, timeout );
    //HttpConnectionParams.setSoTimeout( params, timeout );

    // Register the "http" and "https" protocol schemes, they are
    // required by the default operator to look up socket factories.
    //SchemeRegistry supportedSchemes = new SchemeRegistry();
    //supportedSchemes.register( new Scheme( "http", PlainSocketFactory.getSocketFactory(), 80 ) );
    //supportedSchemes.register( new Scheme( "https", SSLSocketFactory.getSocketFactory(), 443 ) );

    // create http-client
    //setHttpClient( new DefaultHttpClient( new ThreadSafeClientConnManager( params, supportedSchemes ), params ) );
    //setHttpClient( new DefaultHttpClient( params ) );

    HttpClientBuilder b = HttpClientBuilder.create();

    b.setDefaultRequestConfig(RequestConfig.custom().setConnectTimeout(timeout)
            .setConnectionRequestTimeout(timeout).setSocketTimeout(timeout).build());

    //b.setDefaultSocketConfig( SocketConfig.custom()
    //  .setSoTimeout( timeout )
    //  .build() );

    setHttpClient(b.build());
}

From source file:com.adobe.acs.commons.mcp.impl.processes.asset.UrlAssetImport.java

@Override
public void init() throws RepositoryException {
    super.init();
    if (httpFactory != null) {
        HttpClientBuilder clientBuilder = httpFactory.newBuilder();
        clientBuilder.setDefaultSocketConfig(SocketConfig.custom().setSoTimeout(timeout).build());
        clientBuilder.setDefaultRequestConfig(RequestConfig.custom().setConnectTimeout(timeout).build());
        httpClient = clientBuilder.build();
    }// w w w  . j a  v  a  2s  .c  o m
}

From source file:net.sf.jasperreports.phantomjs.ProcessConnection.java

public ProcessConnection(ProcessDirector director, PhantomJSProcess process) {
    this.process = process;

    HttpClientBuilder clientBuilder = HttpClients.custom();

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

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

    this.httpClient = clientBuilder.build();
}

From source file:com.rockagen.commons.http.HttpConn.java

/**
 * Handler main/*from  ww  w  .jav a 2s  .  c  o  m*/
 *
 * @param targetHost target {@link HttpHost}
 * @param proxyHost proxy {@link HttpHost}
 * @param httpRequestMethod HttpGet or HttpPost...
 * @param encoding encoding
 * @param upc {@link UsernamePasswordCredentials}
 * @param keystore keystore stream
 * @param password keystore password
 * @return result String
 * @throws IOException  if an I/O error occurs
 */
protected static String execute(HttpHost targetHost, HttpHost proxyHost, HttpRequest httpRequestMethod,
        String encoding, UsernamePasswordCredentials upc, InputStream keystore, char[] password)
        throws IOException {

    HttpClientBuilder hcb = HttpClients.custom();
    hcb.setDefaultRequestConfig(getRequestConfig());
    if (proxyHost != null) {
        hcb.setProxy(proxyHost);
    }
    if (keystore != null) {

        try {
            KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
            trustStore.load(keystore, password);
            SSLContext sslcontext = SSLContexts.custom()
                    .loadTrustMaterial(trustStore, new TrustSelfSignedStrategy()).build();
            SSLConnectionSocketFactory ssf = new SSLConnectionSocketFactory(sslcontext);
            hcb.setSSLSocketFactory(ssf);
        } catch (KeyStoreException e) {
            log.error("{}", e.getMessage(), e);
        } catch (CertificateException e) {
            log.error("{}", e.getMessage(), e);
        } catch (NoSuchAlgorithmException e) {
            log.error("{}", e.getMessage(), e);
        } catch (KeyManagementException e) {
            log.error("{}", e.getMessage(), e);
        } finally {
            keystore.close();
        }

    }

    if (upc != null) {
        CredentialsProvider cp = new BasicCredentialsProvider();

        AuthScope as = new AuthScope(targetHost);

        cp.setCredentials(as, upc);
        hcb.setDefaultCredentialsProvider(cp);
    }

    CloseableHttpClient chc = hcb.build();
    try {
        CloseableHttpResponse response = chc.execute(targetHost, httpRequestMethod);
        return getResponse(response, encoding);
    } finally {
        chc.close();
    }

}