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:ee.ria.xroad.proxy.clientproxy.ClientProxy.java

private void createClient() throws Exception {
    log.trace("createClient()");

    int timeout = SystemProperties.getClientProxyTimeout();
    int socketTimeout = SystemProperties.getClientProxyHttpClientTimeout();
    RequestConfig.Builder rb = RequestConfig.custom();
    rb.setConnectTimeout(timeout);//from  www.  ja  va 2s.c o  m
    rb.setConnectionRequestTimeout(timeout);
    rb.setSocketTimeout(socketTimeout);

    HttpClientBuilder cb = HttpClients.custom();

    HttpClientConnectionManager connectionManager = getClientConnectionManager();
    cb.setConnectionManager(connectionManager);

    if (SystemProperties.isClientUseIdleConnectionMonitor()) {
        connectionMonitor = new IdleConnectionMonitorThread(connectionManager);
        connectionMonitor
                .setIntervalMilliseconds(SystemProperties.getClientProxyIdleConnectionMonitorInterval());
        connectionMonitor.setConnectionIdleTimeMilliseconds(
                SystemProperties.getClientProxyIdleConnectionMonitorIdleTime());
    }

    cb.setDefaultRequestConfig(rb.build());

    // Disable request retry
    cb.setRetryHandler(new DefaultHttpRequestRetryHandler(0, false));

    client = cb.build();
}

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

protected synchronized HttpClient getHttpClient(final URI uri) throws DSSException {

    if (httpClient != null && !updated) {
        return httpClient;
    }/*from w  w  w. j a  v  a2s  .c o m*/
    if (LOG.isTraceEnabled() && updated) {
        LOG.trace(">>> Proxy preferences updated");
    }
    final HttpClientBuilder httpClientBuilder = configCredentials(uri);
    final RequestConfig.Builder custom = RequestConfig.custom();
    custom.setSocketTimeout(timeoutSocket);
    custom.setConnectionRequestTimeout(timeoutConnection);
    final RequestConfig requestConfig = custom.build();
    httpClientBuilder.setDefaultRequestConfig(requestConfig);
    httpClientBuilder.setConnectionManager(getConnectionManager());

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

From source file:com.ibm.devops.notification.MessageHandlerTest.java

@Test
public void testPostToWebhook() throws IOException {
    HttpClientBuilder httpClientBuilder = PowerMockito.mock(HttpClientBuilder.class);
    CloseableHttpClient httpClient = PowerMockito.mock(CloseableHttpClient.class);
    CloseableHttpResponse response = PowerMockito.mock(CloseableHttpResponse.class);
    PowerMockito.mockStatic(HttpClients.class);
    StatusLine statusLine = mock(StatusLine.class);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    PrintStream printStream = new PrintStream(baos);
    String content;//  w w w .  j av  a2  s  .c o  m
    JSONObject message = new JSONObject();

    RequestConfig defaultRequestConfig = RequestConfig.custom().setSocketTimeout(5000).setConnectTimeout(5000)
            .setConnectionRequestTimeout(5000).build();
    when(HttpClients.custom()).thenReturn(httpClientBuilder);
    when(httpClientBuilder.setDefaultRequestConfig(defaultRequestConfig).build()).thenReturn(httpClient);
    when(httpClient.execute(any(HttpPost.class))).thenReturn(response);
    when(response.getStatusLine()).thenReturn(statusLine);
    when(statusLine.toString()).thenReturn("200");

    assertTrue(Util.isNullOrEmpty(""));
    assertTrue(Util.isNullOrEmpty(null));

    MessageHandler.postToWebhook("", false, message, printStream);
    content = new String(baos.toByteArray(), StandardCharsets.UTF_8);

    assertTrue(content.contains("[IBM Cloud DevOps] IBM_CLOUD_DEVOPS_WEBHOOK_URL not set."));

    MessageHandler.postToWebhook("http://fakewebhook", false, message, printStream);
    content = new String(baos.toByteArray(), StandardCharsets.UTF_8);
    assertTrue(content.contains("[IBM Cloud DevOps] Message successfully posted to webhook."));

    when(statusLine.toString()).thenReturn("400");
    MessageHandler.postToWebhook("http://fakewebhook", false, message, printStream);
    content = new String(baos.toByteArray(), StandardCharsets.UTF_8);
    assertTrue(content.contains("[IBM Cloud DevOps] Message failed, response status:"));

    when(httpClient.execute(any(HttpPost.class))).thenThrow(new IOException("..."));
    MessageHandler.postToWebhook("http://fakewebhook", false, message, printStream);
    content = new String(baos.toByteArray(), StandardCharsets.UTF_8);
    assertTrue(content.contains("[IBM Cloud DevOps] IOException, could not post to webhook:"));
}

From source file:com.ibm.devops.notification.MessageHandlerTest.java

@Test
public void testPostDeployableMessageToWebhook() throws IOException {
    HttpClientBuilder httpClientBuilder = PowerMockito.mock(HttpClientBuilder.class);
    CloseableHttpClient httpClient = PowerMockito.mock(CloseableHttpClient.class);
    CloseableHttpResponse response = PowerMockito.mock(CloseableHttpResponse.class);
    PowerMockito.mockStatic(HttpClients.class);
    StatusLine statusLine = mock(StatusLine.class);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    PrintStream printStream = new PrintStream(baos);
    String content;//from ww  w  .ja  v  a  2 s  . co m
    JSONObject message = new JSONObject();

    RequestConfig defaultRequestConfig = RequestConfig.custom().setSocketTimeout(5000).setConnectTimeout(5000)
            .setConnectionRequestTimeout(5000).build();
    when(HttpClients.custom()).thenReturn(httpClientBuilder);
    when(httpClientBuilder.setDefaultRequestConfig(defaultRequestConfig).build()).thenReturn(httpClient);
    when(httpClient.execute(any(HttpPost.class))).thenReturn(response);
    when(response.getStatusLine()).thenReturn(statusLine);
    when(statusLine.toString()).thenReturn("200");

    assertTrue(Util.isNullOrEmpty(""));
    assertTrue(Util.isNullOrEmpty(null));

    MessageHandler.postToWebhook("", true, message, printStream);
    content = new String(baos.toByteArray(), StandardCharsets.UTF_8);
    System.out.println("content: " + content);
    assertTrue(content.contains("[IBM Cloud DevOps] IBM_CLOUD_DEVOPS_WEBHOOK_URL not set."));

    MessageHandler.postToWebhook("http://fakewebhook", true, message, printStream);
    content = new String(baos.toByteArray(), StandardCharsets.UTF_8);
    assertTrue(content.contains("[IBM Cloud DevOps] Message successfully posted to webhook."));

    when(statusLine.toString()).thenReturn("400");
    MessageHandler.postToWebhook("http://fakewebhook", true, message, printStream);
    content = new String(baos.toByteArray(), StandardCharsets.UTF_8);
    assertTrue(content.contains("[IBM Cloud DevOps] Message failed, response status:"));

    when(httpClient.execute(any(HttpPost.class))).thenThrow(new IOException("..."));
    MessageHandler.postToWebhook("http://fakewebhook", true, message, printStream);
    content = new String(baos.toByteArray(), StandardCharsets.UTF_8);
    assertTrue(content.contains("[IBM Cloud DevOps] IOException, could not post to webhook:"));

    message = new JSONObject();
    message.put("Org",
            "{\"Name\": \"darth_vador@ibm.com\", \"Guid\": \"1b45b640-ff52-4f94-8009-9af44aa9f9c8\"}");
    message.put("Space", "{\"Name\": \"dev\", \"Guid\": \"838b41a6-58e0-4c05-aaf4-817925d42332\"}");
    message.put("App", "{\"Name\": \"node-hello-world\", \"Guid\": \"a7820d14-9d5d-40c7-a58c-43caeaf8cb75\"}");
    message.put("ApiEndpoint", "https://api.stage1.ng.bluemix.net");
    message.put("Method", "POST");
    message.put("GitData",
            "[{\"GitURL\": \"https://github.com/dvador/simple-node-app.git\", \"GitBranch\": \"origin/master\", \"GitCommitID\": \"590c229c64ef246e5742744449963dc74493cb8a\"}]");

    when(httpClient.execute(any(HttpPost.class))).thenReturn(response);
    MessageHandler.postToWebhook("http://fakewebhook", true, message, printStream);
    content = new String(baos.toByteArray(), StandardCharsets.UTF_8);
    assertTrue(content.contains("[IBM Cloud DevOps] Message successfully posted to webhook."));
}

From source file:leap.lang.http.client.apache.ApacheHttpClient.java

protected CloseableHttpClient initHttpClient() {
    HttpClientBuilder cb = HttpClientBuilder.create();

    //TODO : small buffer size will cause socket closed when reading response entity?
    PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(getDefaultRegistry());
    //cm.setDefaultConnectionConfig(ConnectionConfig.custom().setBufferSize(1024 * 1024).build());

    cm.setMaxTotal(maxConnectionTotal);/* w w w. j a v  a  2s  .  c  om*/
    cm.setDefaultMaxPerRoute(maxConnectionPerRoute);

    if (bufferSize > 0) {
        ConnectionConfig cc = ConnectionConfig.copy(ConnectionConfig.DEFAULT).setBufferSize(bufferSize).build();

        cm.setDefaultConnectionConfig(cc);
    }

    cb.setRetryHandler(new HttpRequestRetryHandler() {
        @Override
        public boolean retryRequest(IOException exception, int executionCount, HttpContext context) {
            return false;
        }
    });

    cb.setConnectionManager(cm);
    cb.setDefaultRequestConfig(requestConfig);

    return cb.build();
}

From source file:com.gargoylesoftware.htmlunit.HttpWebConnection.java

private void configureTimeout(final HttpClientBuilder builder, final int timeout) {
    final RequestConfig.Builder requestBuilder = createRequestConfigBuilder(timeout);
    builder.setDefaultRequestConfig(requestBuilder.build());

    builder.setDefaultSocketConfig(createSocketConfigBuilder(timeout).build());

    httpContext_.removeAttribute(HttpClientContext.REQUEST_CONFIG);
    usedOptions_.setTimeout(timeout);//from w w w. j  av  a 2s  .c  o m
}

From source file:com.norconex.collector.http.client.impl.GenericHttpClientFactory.java

@Override
public HttpClient createHTTPClient(String userAgent) {
    HttpClientBuilder builder = HttpClientBuilder.create();
    builder.setSslcontext(createSSLContext());
    builder.setSchemePortResolver(createSchemePortResolver());
    builder.setDefaultRequestConfig(createRequestConfig());
    builder.setProxy(createProxy());/*  ww  w  .j a  va 2 s . c  om*/
    builder.setDefaultCredentialsProvider(createCredentialsProvider());
    builder.setDefaultConnectionConfig(createConnectionConfig());
    builder.setUserAgent(userAgent);
    builder.setMaxConnTotal(maxConnections);
    //builder.setMaxConnPerRoute(maxConnPerRoute)
    buildCustomHttpClient(builder);

    //TODO Put in place a more permanent solution to the following
    //Fix GitHub #17 start
    RedirectStrategy strategy = createRedirectStrategy();
    if (strategy == null) {
        strategy = LaxRedirectStrategy.INSTANCE;
    }
    builder.setRedirectStrategy(new TargetURLRedirectStrategy(strategy));
    //Fix end

    HttpClient httpClient = builder.build();
    if (AUTH_METHOD_FORM.equalsIgnoreCase(authMethod)) {
        authenticateUsingForm(httpClient);
    }
    return httpClient;
}

From source file:eu.europa.esig.dss.client.http.commons.CommonsDataLoader.java

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

    if ((httpClient != null) && !updated) {
        return httpClient;
    }//from w w w .jav  a  2  s. c o  m
    if (LOG.isTraceEnabled() && updated) {
        LOG.trace(">>> Proxy preferences updated");
    }
    HttpClientBuilder httpClientBuilder = HttpClients.custom();

    httpClientBuilder = configCredentials(httpClientBuilder, url);

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

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

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));
        }/*from  www  .j a v  a  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();
    }
}

From source file:jp.co.ctc_g.jse.core.rest.springmvc.client.ProxyClientHttpRequestFactory.java

/**
 * ???????HttpClient????????//ww  w .  jav a2  s  . co  m
 * {@inheritDoc}
 */
@Override
public void afterPropertiesSet() throws Exception {

    Assert.notNull(proxyHost, "(proxyHost)???");
    Assert.notNull(proxyPort, "??(proxyPort)???");

    PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager();
    connectionManager.setMaxTotal(maxTotal);
    connectionManager.setDefaultMaxPerRoute(defaultMaxPerRoute);

    HttpClientBuilder builder = HttpClients.custom();
    builder.setConnectionManager(connectionManager);
    if (authentication) {
        Assert.notNull(username,
                "??true???????(username)???");
        Assert.notNull(password,
                "??true?????(password)???");
        DefaultProxyRoutePlanner routePlanner = new DefaultProxyRoutePlanner(
                new HttpHost(proxyHost, Integer.parseInt(proxyPort)));
        builder.setRoutePlanner(routePlanner);
        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(new AuthScope(proxyHost, Integer.parseInt(proxyPort)),
                new UsernamePasswordCredentials(username, password));
        builder.setDefaultCredentialsProvider(credsProvider);
    }
    builder.setDefaultRequestConfig(RequestConfig.custom().setSocketTimeout(readTimeout).build());
    CloseableHttpClient client = builder.build();
    setHttpClient(client);
}