Example usage for org.apache.http.impl.client HttpClients custom

List of usage examples for org.apache.http.impl.client HttpClients custom

Introduction

In this page you can find the example usage for org.apache.http.impl.client HttpClients custom.

Prototype

public static HttpClientBuilder custom() 

Source Link

Document

Creates builder object for construction of custom CloseableHttpClient instances.

Usage

From source file:com.uber.jaeger.httpclient.JaegerRequestAndResponseInterceptorIntegrationTest.java

@Test
public void testHttpClientTracing() throws Exception {
    HttpClientBuilder clientBuilder = HttpClients.custom();
    CloseableHttpClient client = TracingInterceptors.addTo(clientBuilder, tracer).build();

    //Make a request to the async client and wait for response
    client.execute(new HttpHost("localhost", mockServerRule.getPort()),
            new BasicHttpRequest("GET", "/testing"));

    verifyTracing(parentSpan);//from  ww  w  . ja v  a 2 s .com
}

From source file:ee.ria.xroad.common.opmonitoring.OpMonitoringDaemonHttpClient.java

/**
 * Creates HTTP client./*from  www .j  a  va 2  s .co  m*/
 * @param authKey the client's authentication key
 * @param clientMaxTotalConnections client max total connections
 * @param clientMaxConnectionsPerRoute client max connections per route
 * @param connectionTimeoutMilliseconds connection timeout in milliseconds
 * @param socketTimeoutMilliseconds socket timeout in milliseconds
 * @return HTTP client
 * @throws Exception if creating a HTTPS client and SSLContext
 * initialization fails
 */
public static CloseableHttpClient createHttpClient(InternalSSLKey authKey, int clientMaxTotalConnections,
        int clientMaxConnectionsPerRoute, int connectionTimeoutMilliseconds, int socketTimeoutMilliseconds)
        throws Exception {
    log.trace("createHttpClient()");

    RegistryBuilder<ConnectionSocketFactory> sfr = RegistryBuilder.<ConnectionSocketFactory>create();

    if ("https".equalsIgnoreCase(OpMonitoringSystemProperties.getOpMonitorDaemonScheme())) {
        sfr.register("https", createSSLSocketFactory(authKey));
    } else {
        sfr.register("http", PlainConnectionSocketFactory.INSTANCE);
    }

    PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(sfr.build());
    cm.setMaxTotal(clientMaxTotalConnections);
    cm.setDefaultMaxPerRoute(clientMaxConnectionsPerRoute);
    cm.setDefaultSocketConfig(SocketConfig.custom().setTcpNoDelay(true).build());

    RequestConfig.Builder rb = RequestConfig.custom().setConnectTimeout(connectionTimeoutMilliseconds)
            .setConnectionRequestTimeout(connectionTimeoutMilliseconds)
            .setSocketTimeout(socketTimeoutMilliseconds);

    HttpClientBuilder cb = HttpClients.custom().setConnectionManager(cm).setDefaultRequestConfig(rb.build());

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

    return cb.build();
}

From source file:org.aliuge.crawler.fetcher.DefaultFetcher.java

public DefaultFetcher createFetcher(FetchConfig config) {
    // /*from   w  ww .  ja va2s .c o m*/
    connectionManager = new PoolingHttpClientConnectionManager();

    BasicCookieStore cookieStore = new BasicCookieStore();
    CookieSpecProvider easySpecProvider = new CookieSpecProvider() {
        public CookieSpec create(HttpContext context) {

            return new BrowserCompatSpec() {
                @Override
                public void validate(Cookie cookie, CookieOrigin origin) throws MalformedCookieException {
                    // Oh, I am easy
                }
            };
        }

    };
    Registry<CookieSpecProvider> r = RegistryBuilder.<CookieSpecProvider>create()
            .register(CookieSpecs.BEST_MATCH, new BestMatchSpecFactory())
            .register(CookieSpecs.BROWSER_COMPATIBILITY, new BrowserCompatSpecFactory())
            .register("easy", easySpecProvider).build();

    // Create global request configuration
    defaultRequestConfig = RequestConfig.custom().setCookieSpec("easy").setSocketTimeout(10000)
            .setConnectTimeout(10000).build();

    connectionManager.setMaxTotal(config.getMaxTotalConnections());
    connectionManager.setDefaultMaxPerRoute(config.getMaxConnectionsPerHost());

    // Create an HttpClient with the given custom dependencies and
    // configuration.
    httpClient = HttpClients.custom().setConnectionManager(connectionManager).setDefaultCookieStore(cookieStore)
            .setDefaultCookieSpecRegistry(r)
            /* .setProxy(new HttpHost("myproxy", 8080)) */
            .setDefaultRequestConfig(defaultRequestConfig).build();

    if (connectionMonitorThread == null) {
        connectionMonitorThread = new IdleConnectionMonitorThread(connectionManager);
    }
    /*
     * connectionMonitorThread.start(); try {
     * connectionMonitorThread.join(); } catch (InterruptedException e) { //
     * TODO Auto-generated catch block e.printStackTrace(); }
     */
    return this;
}

From source file:com.redhat.developers.msa.ola.OlaController.java

/**
 * This is were the "magic" happens: it creates a Feign, which is a proxy interface for remote calling a REST endpoint with
 * Hystrix fallback support./*from  w  w w  .  ja  va2s . c om*/
 *
 * @return The feign pointing to the service URL and with Hystrix fallback.
 */
private HolaService getNextService() {
    // This stores the Original/Parent ServerSpan from ZiPkin.
    final ServerSpan serverSpan = brave.serverSpanThreadBinder().getCurrentServerSpan();
    final CloseableHttpClient httpclient = HttpClients.custom()
            .addInterceptorFirst(new BraveHttpRequestInterceptor(brave.clientRequestInterceptor(),
                    new DefaultSpanNameProvider()))
            .addInterceptorFirst(new BraveHttpResponseInterceptor(brave.clientResponseInterceptor())).build();
    return HystrixFeign.builder()
            // Use apache HttpClient which contains the ZipKin Interceptors
            .client(new ApacheHttpClient(httpclient))
            // Bind Zipkin Server Span to Feign Thread
            .requestInterceptor((t) -> brave.serverSpanThreadBinder().setCurrentSpan(serverSpan))
            .logger(new Logger.ErrorLogger()).logLevel(Level.BASIC).decoder(new JacksonDecoder())
            .target(HolaService.class, "http://hola:8080/",
                    () -> Collections.singletonList("Hola response (fallback)"));
}

From source file:org.ow2.proactive_grid_cloud_portal.rm.server.serialization.CatalogRequestBuilder.java

private HttpClientBuilder getHttpClientBuilder()
        throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException {
    SSLContextBuilder sslContextBuilder = new SSLContextBuilder();
    sslContextBuilder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
    SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContextBuilder.build(),
            SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    return HttpClients.custom().setSSLSocketFactory(sslSocketFactory);
}

From source file:org.jboss.as.test.integration.web.security.servlet3.ServletSecurityRoleNamesCommon.java

/**
 * Method that needs to be overridden with the HTTPClient code.
 *
 * @param user         username/*from  w ww.ja va  2 s  .  co m*/
 * @param pass         password
 * @param expectedCode http status code
 * @throws Exception
 */
protected void makeCall(String user, String pass, int expectedCode, URL url) throws Exception {
    CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(new AuthScope(url.getHost(), url.getPort()),
            new UsernamePasswordCredentials(user, pass));
    try (CloseableHttpClient httpclient = HttpClients.custom()
            .setDefaultCredentialsProvider(credentialsProvider).build()) {

        HttpGet httpget = new HttpGet(url.toExternalForm());

        HttpResponse response = httpclient.execute(httpget);
        HttpEntity entity = response.getEntity();

        StatusLine statusLine = response.getStatusLine();
        assertEquals(expectedCode, statusLine.getStatusCode());

        EntityUtils.consume(entity);
    }
}

From source file:com.olacabs.fabric.processors.httpwriter.HttpWriter.java

/**
 * Starts the HttpClient and Manager./*from   w w  w . j  av a2  s .c o m*/
 */
protected void start(AuthConfiguration authConfiguration, Boolean authEnabledParam)
        throws InitializationException {
    this.manager = new PoolingHttpClientConnectionManager();
    manager.setMaxTotal(poolSize);
    manager.setDefaultMaxPerRoute(poolSize);
    //client = HttpClients.custom().setConnectionManager(manager).build();
    httpClientBuilder = HttpClients.custom();
    httpClientBuilder.setConnectionManager(manager);
    if (authEnabledParam) {
        setAuth(authConfiguration, httpClientBuilder);
    }
    client = httpClientBuilder.build();
}

From source file:jchat.test.RestTest.java

@Test
public void test() throws Exception {
    eao.withQuery("DELETE FROM " + MessageEntity.class.getName(), new BaseEAO.ExecutableQuery<Integer>() {
        @Override/*from   w  ww.  jav a2  s. c o m*/
        public Integer execute(Query query) {
            return query.executeUpdate();
        }
    });
    CloseableHttpClient client = HttpClients.custom().build();

    // If this fails, don't forget to change you JS code
    Assert.assertEquals("{\"messageDto\":[]}",
            getBody(client.execute(new HttpGet(deploymentURL.toURI() + "rest/messages"))));

    String text = "Hi there! [" + System.currentTimeMillis() + "]";
    try {
        // login
        post(client, "rest/auth", new BasicNameValuePair("user", "bototaxi"));
        // post message
        post(client, "rest/messages", new BasicNameValuePair("message", text));

        int tryCounter = 0;
        while (true) {
            String json = getBody(client.execute(new HttpGet(deploymentURL.toURI() + "rest/messages")));
            if (json.contains(text)) {
                break;
            }

            if (++tryCounter > 10) {
                Assert.fail("We tried " + tryCounter + " times without success. message: [" + text
                        + "]; JSON: [" + json + "]");
            }

            // Not time enough to process the message. Try it again!
            Thread.sleep(500);
        }

    } finally {
        client.close();
    }
}