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.thevortex.lighting.jinks.client.WinkClient.java

/**
 * Basic setup for a client builder, including the connection manager.
 *
 * @return the builder/*from ww  w  . ja  v  a2 s.  c o m*/
 */
public synchronized CloseableHttpClient getClient() {
    if (httpClient == null) {
        PoolingHttpClientConnectionManager mgr = new PoolingHttpClientConnectionManager(1, TimeUnit.MINUTES);
        mgr.setDefaultMaxPerRoute(5);
        mgr.setMaxTotal(15);

        HttpClientBuilder httpClientBuilder = HttpClientBuilder.create().setConnectionManager(mgr);
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(connectionTimeout * 1000)
                .setSocketTimeout(socketTimeout * 1000).build();
        httpClient = httpClientBuilder.setDefaultRequestConfig(requestConfig).build();
    }
    return httpClient;
}

From source file:com.jaspersoft.studio.data.adapter.JSSBuiltinDataFileServiceFactory.java

@Override
public DataFileService createService(JasperReportsContext context, DataFile dataFile) {
    if (dataFile instanceof RepositoryDataLocation) {
        return new RepositoryDataLocationService(context, (RepositoryDataLocation) dataFile);
    }/*from w w  w .  jav a 2  s  .co  m*/
    if (dataFile instanceof HttpDataLocation) {
        return new HttpDataService(context, (HttpDataLocation) dataFile) {
            @Override
            protected CloseableHttpClient createHttpClient(Map<String, Object> parameters) {
                HttpClientBuilder clientBuilder = HttpClients.custom();
                HttpUtils.setupProxy(clientBuilder);
                // 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);

                HttpClientContext clientContext = HttpClientContext.create();

                setAuthentication(parameters, clientContext);

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

From source file:com.normalexception.app.rx8club.html.LoginFactory.java

/**
 * Initialize the client, cookie store, and context
 *///from   ww  w.  java 2  s .c  o m
private void initializeClientInformation() {
    Log.d(TAG, "Initializing Client...");

    /*
    Log.d(TAG, "Creating Custom Cache Configuration");
    CacheConfig cacheConfig = CacheConfig.custom()
      .setMaxCacheEntries(1000)
      .setMaxObjectSize(8192)
      .build();
    */

    Log.d(TAG, "Creating Custom Request Configuration");
    RequestConfig rConfig = RequestConfig.custom().setCircularRedirectsAllowed(true)
            .setConnectionRequestTimeout(TIMEOUT).setSocketTimeout(TIMEOUT).build();

    cookieStore = new BasicCookieStore();
    httpContext = new BasicHttpContext();

    Log.d(TAG, "Building Custom HTTP Client");
    HttpClientBuilder httpclientbuilder = HttpClients.custom();
    //httpclientbuilder.setCacheConfig(cacheConfig);
    httpclientbuilder.setDefaultRequestConfig(rConfig);
    httpclientbuilder.setDefaultCookieStore(cookieStore);

    Log.d(TAG, "Connection Manager Initializing");
    PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
    cm.setMaxTotal(200);
    cm.setDefaultMaxPerRoute(20);
    httpclientbuilder.setConnectionManager(cm);

    Log.d(TAG, "Enable GZIP Compression");
    httpclientbuilder.addInterceptorLast(new HttpRequestInterceptor() {

        public void process(final HttpRequest request, final HttpContext context)
                throws HttpException, IOException {
            if (!request.containsHeader("Accept-Encoding")) {
                request.addHeader("Accept-Encoding", "gzip");
            }
        }

    });
    httpclientbuilder.addInterceptorLast(new HttpResponseInterceptor() {

        public void process(final HttpResponse response, final HttpContext context)
                throws HttpException, IOException {
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                Header ceheader = entity.getContentEncoding();
                if (ceheader != null) {
                    HeaderElement[] codecs = ceheader.getElements();
                    for (int i = 0; i < codecs.length; i++) {
                        if (codecs[i].getName().equalsIgnoreCase("gzip")) {
                            response.setEntity(new GzipDecompressingEntity(response.getEntity()));
                            return;
                        }
                    }
                }
            }
        }

    });

    // Follow Redirects
    Log.d(TAG, "Registering Redirect Strategy");
    httpclientbuilder.setRedirectStrategy(new RedirectStrategy());

    // Setup retry handler
    Log.d(TAG, "Registering Retry Handler");
    httpclientbuilder.setRetryHandler(new RetryHandler());

    // Setup KAS
    Log.d(TAG, "Registering Keep Alive Strategy");
    httpclientbuilder.setKeepAliveStrategy(new KeepAliveStrategy());

    httpclient = httpclientbuilder.build();

    //httpclient.log.enableDebug(
    //      MainApplication.isHttpClientLogEnabled());

    isInitialized = true;
}

From source file:org.nuxeo.connect.downloads.LocalDownloadingPackage.java

@Override
public void run() {
    setPackageState(PackageState.REMOTE);
    HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
    RequestConfig.Builder requestConfigBuilder = RequestConfig.custom().setSocketTimeout(SO_TIMEOUT_MS)
            .setConnectTimeout(CONNECTION_TIMEOUT_MS);
    CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    ProxyHelper.configureProxyIfNeeded(requestConfigBuilder, credentialsProvider, sourceUrl);
    httpClientBuilder.setDefaultRequestConfig(requestConfigBuilder.build());
    httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);

    try (CloseableHttpClient httpClient = httpClientBuilder.build()) {
        setPackageState(PackageState.DOWNLOADING);
        HttpGet method = new HttpGet(sourceUrl);
        if (!sourceUrl.contains(ConnectUrlConfig.CONNECT_TEST_MODE_BASEURL + "test")) { // for testing
            Map<String, String> headers = SecurityHeaderGenerator.getHeaders();
            for (String headerName : headers.keySet()) {
                method.addHeader(headerName, headers.get(headerName));
            }//from  w  w w  . ja v  a2 s.c o m
        }
        try (CloseableHttpResponse httpResponse = httpClient.execute(method)) {
            int rc = httpResponse.getStatusLine().getStatusCode();
            switch (rc) {
            case HttpStatus.SC_OK:
                if (sourceSize == 0) {
                    Header clheader = httpResponse.getFirstHeader("content-length");
                    if (clheader != null) {
                        sourceSize = Long.parseLong(clheader.getValue());
                    }
                }
                InputStream in = httpResponse.getEntity().getContent();
                saveStreamAsFile(in);
                registerDownloadedPackage();
                setPackageState(PackageState.DOWNLOADED);
                break;

            case HttpStatus.SC_NOT_FOUND:
                throw new ConnectServerError(String.format("Package not found (%s).", rc));
            case HttpStatus.SC_FORBIDDEN:
                throw new ConnectServerError(String.format("Access refused (%s).", rc));
            case HttpStatus.SC_UNAUTHORIZED:
                throw new ConnectServerError(String.format("Registration required (%s).", rc));
            default:
                serverError = true;
                throw new ConnectServerError(String.format("Connect server HTTP response code %s.", rc));
            }
        }
    } catch (IOException e) { // Expected SocketTimeoutException or ConnectTimeoutException
        serverError = true;
        setPackageState(PackageState.REMOTE);
        log.debug(e, e);
        errorMessage = e.getMessage();
    } catch (ConnectServerError e) {
        setPackageState(PackageState.REMOTE);
        log.debug(e, e);
        errorMessage = e.getMessage();
    } finally {
        ConnectDownloadManager cdm = NuxeoConnectClient.getDownloadManager();
        cdm.removeDownloadingPackage(getId());
        completed = true;
    }
}

From source file:org.kuali.rice.ksb.messaging.serviceconnectors.DefaultHttpClientConfigurer.java

/**
 * Customizes the configuration of the httpClientBuilder.
 *
 * <p>Internally, this uses several helper methods to assist with configuring:
 * <ul>//from  w  w w .j  a  va 2s.  c  o m
 *     <li>Calls {@link #buildConnectionManager()} and sets the resulting {@link HttpClientConnectionManager} (if
 *     non-null) into the httpClientBuilder.</li>
 *     <li>Calls {@link #buildRequestConfig()} and sets the resulting {@link RequestConfig} (if non-null) into the
 *     httpClientBuilder.</li>
 *     <li>Calls {@link #buildRetryHandler()} and sets the resulting {@link HttpRequestRetryHandler} (if non-null)
 *     into the httpClientBuilder.</li>
 * </ul>
 * </p>
 *
 * @param httpClientBuilder the httpClientBuilder being configured
 */
@Override
public void customizeHttpClient(HttpClientBuilder httpClientBuilder) {

    HttpClientConnectionManager connectionManager = buildConnectionManager();
    if (connectionManager != null) {
        httpClientBuilder.setConnectionManager(connectionManager);
    }

    RequestConfig requestConfig = buildRequestConfig();
    if (requestConfig != null) {
        httpClientBuilder.setDefaultRequestConfig(requestConfig);
    }

    HttpRequestRetryHandler retryHandler = buildRetryHandler();
    if (retryHandler != null) {
        httpClientBuilder.setRetryHandler(retryHandler);
    }
}

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

/**
 * Sharepoint requires NTLM. This client requires a non-null user/passwd/domain.
 * //from  ww  w  .j av a  2s .  co m
 */
@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.ibm.team.build.internal.hjplugin.util.HttpUtils.java

/**
 * Because the creation of the SSLConnectionSocketFactory is expensive (reads from disk
 * the certs file) we will cache the client. The client is re-used so doesn't have any
 * target RTC server info associated with it.
 * @return an HttpClient/* w ww  . j  a  v a2  s.c  o  m*/
 * @throws GeneralSecurityException
 */
private synchronized static CloseableHttpClient getClient() throws GeneralSecurityException {
    if (HTTP_CLIENT == null) {
        HttpClientBuilder clientBuilder = HttpClientBuilder.create();

        clientBuilder.setSSLSocketFactory(getSSLConnectionSocketFactory());

        // TODO to find out if this is sufficient, we can periodically dump the PoolStats
        clientBuilder.setMaxConnPerRoute(10);
        clientBuilder.setMaxConnTotal(100);

        // allow redirects on POST
        clientBuilder.setRedirectStrategy(new LaxRedirectStrategy());

        // How long to wait to get a connection from our connection manager. The default
        // timeouts are forever which is probably not good. 
        // TODO If we set it when creating the GET, PUT & POST maybe its not really needed here
        RequestConfig config = getRequestConfig(CONNECTION_REQUEST_TIMEOUT);
        clientBuilder.setDefaultRequestConfig(config);

        // This will create a client with the defaults (which includes the PoolingConnectionManager)
        HTTP_CLIENT = clientBuilder.build();
    }

    return HTTP_CLIENT;
}

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 a  2s  .  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:de.taimos.httputils.HTTPRequest.java

private HttpResponse execute(final HttpUriRequest req) {
    final HttpClientBuilder builder = HttpClientBuilder.create();
    final Builder reqConfig = RequestConfig.custom();
    if (this.timeout != null) {
        reqConfig.setConnectTimeout(this.timeout);
    }//from ww w  .j  a v a  2s .c  om
    reqConfig.setRedirectsEnabled(this.followRedirect);
    builder.setDefaultRequestConfig(reqConfig.build());
    if ((this.userAgent != null) && !this.userAgent.isEmpty()) {
        builder.setUserAgent(this.userAgent);
    }
    try {
        final CloseableHttpClient httpclient = builder.build();
        // if request has data populate body
        if (req instanceof HttpEntityEnclosingRequestBase) {
            final HttpEntityEnclosingRequestBase entityBase = (HttpEntityEnclosingRequestBase) req;
            entityBase.setEntity(new StringEntity(this.body, "UTF-8"));
        }
        // Set headers
        final Set<Entry<String, List<String>>> entrySet = this.headers.entrySet();
        for (final Entry<String, List<String>> entry : entrySet) {
            final List<String> list = entry.getValue();
            for (final String string : list) {
                req.addHeader(entry.getKey(), string);
            }
        }

        final HttpResponse response = httpclient.execute(req);
        return response;
    } catch (final ClientProtocolException e) {
        throw new RuntimeException(e);
    } catch (final IOException e) {
        throw new RuntimeException(e);
    }
}