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:org.alfresco.tutorials.webscripts.HelloWorldWebScriptIT.java

@Test
public void testWebScriptCall() throws Exception {
    String webscriptURL = "http://localhost:8080/alfresco/service/sample/helloworld";
    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(new AuthScope("localhost", 8080),
            new UsernamePasswordCredentials(ALFRESCO_USERNAME, ALFRESCO_PWD));
    CloseableHttpClient httpclient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build();

    try {//from   www . j a  v  a  2 s .c  o m
        HttpGet httpget = new HttpGet(webscriptURL);
        HttpResponse httpResponse = httpclient.execute(httpget);
        assertEquals("HTTP Response Status is not OK(200)", HttpStatus.SC_OK,
                httpResponse.getStatusLine().getStatusCode());
        HttpEntity entity = httpResponse.getEntity();
        assertNotNull("Response from Web Script is null", entity);
        String response = EntityUtils.toString(entity);
        JSONParser parser = new JSONParser();
        JSONObject jsonResponseObj = (JSONObject) parser.parse(response);
        assertTrue("Folder not found", (boolean) jsonResponseObj.get("foundFolder"));
        assertTrue("Doc not found", (boolean) jsonResponseObj.get("foundDoc"));
    } finally {
        httpclient.close();
    }
}

From source file:gobblin.compaction.audit.KafkaAuditCountHttpClient.java

/**
 * Constructor/*from   www.ja v a2  s. com*/
 */
public KafkaAuditCountHttpClient(State state) {
    int maxTotal = state.getPropAsInt(CONNECTION_MAX_TOTAL, DEFAULT_CONNECTION_MAX_TOTAL);
    int maxPerRoute = state.getPropAsInt(MAX_PER_ROUTE, DEFAULT_MAX_PER_ROUTE);

    cm = new PoolingHttpClientConnectionManager();
    cm.setMaxTotal(maxTotal);
    cm.setDefaultMaxPerRoute(maxPerRoute);
    httpClient = HttpClients.custom().setConnectionManager(cm).build();

    this.baseUrl = state.getProp(KAFKA_AUDIT_REST_BASE_URL);
    this.maxNumTries = state.getPropAsInt(KAFKA_AUDIT_REST_MAX_TRIES, 5);
    this.startQueryString = state.getProp(KAFKA_AUDIT_REST_START_QUERYSTRING_KEY,
            KAFKA_AUDIT_REST_START_QUERYSTRING_DEFAULT);
    this.endQueryString = state.getProp(KAFKA_AUDIT_REST_END_QUERYSTRING_KEY,
            KAFKA_AUDIT_REST_END_QUERYSTRING_DEFAULT);
}

From source file:org.wso2.apim.billing.services.impl.WorkflowClientImpl.java

private HttpResponse sendPOSTMessage(String url, List<NameValuePair> headers, List<NameValuePair> urlParameters)
        throws Exception {
    CloseableHttpClient httpClient = HttpClients.custom()
            .setHostnameVerifier(SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER).build();
    HttpPost post = new HttpPost(url);
    if (headers != null) {
        for (NameValuePair nameValuePair : headers) {
            post.addHeader(nameValuePair.getName(), nameValuePair.getValue());
        }/*from   w w w. ja va2 s .  c o m*/
    }
    post.setEntity(new UrlEncodedFormEntity(urlParameters));
    return httpClient.execute(post);
}

From source file:org.mule.modules.apifortress.ApiFortressClient.java

/**
 * Constructor//from   w ww. ja va  2 s  .co  m
 * @param config the connector config. Won't be referenced
 */
public ApiFortressClient(Config config) {
    super();

    connectionManager = new PoolingHttpClientConnectionManager();
    connectionManager.setMaxTotal(config.getTotalConnections());

    final RequestConfig requestConfig = RequestConfig.custom()
            .setConnectTimeout(config.getConnectTimeout() * 1000)
            .setSocketTimeout(config.getSocketTimeout() * 1000).build();
    client = HttpClients.custom().setConnectionManager(connectionManager).setDefaultRequestConfig(requestConfig)
            .build();
    silent = config.isSilent();
    dryRun = config.isDryRun();
    threshold = config.getThreshold();

}

From source file:co.paralleluniverse.fibers.servlet.FiberHttpServletTest.java

@Test
public void testRedirect() throws IOException, InterruptedException, Exception {
    for (int i = 0; i < 10; i++) {
        final HttpGet httpGet = new HttpGet("http://localhost:8080/redirect");
        final CloseableHttpResponse res = HttpClients.custom().disableRedirectHandling().build()
                .execute(httpGet);/*ww w .ja  v a  2 s. c  o  m*/
        assertEquals(302, res.getStatusLine().getStatusCode());
        assertTrue(res.getFirstHeader("Location").getValue().endsWith("/foo"));
    }
}

From source file:com.liferay.jsonwebserviceclient.JSONWebServiceClientImpl.java

public void afterPropertiesSet() {
    HttpClientBuilder httpClientBuilder = HttpClients.custom();

    httpClientBuilder.setConnectionManager(getPoolingHttpClientConnectionManager());

    if ((_login != null) && (_password != null)) {
        CredentialsProvider credentialsProvider = new BasicCredentialsProvider();

        credentialsProvider.setCredentials(new AuthScope(_hostName, _hostPort),
                new UsernamePasswordCredentials(_login, _password));

        httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
        httpClientBuilder.setRetryHandler(new HttpRequestRetryHandlerImpl());
    } else {/*from w  w  w.j ava2 s  .c om*/
        if (_logger.isWarnEnabled()) {
            _logger.warn("Login and password are required");
        }
    }

    try {
        setProxyHost(httpClientBuilder);

        _closeableHttpClient = httpClientBuilder.build();

        if (_logger.isDebugEnabled()) {
            _logger.debug("Configured client for " + _protocol + "://" + _hostName);
        }
    } catch (Exception e) {
        _logger.error("Unable to configure client", e);
    }
}

From source file:fi.helsinki.moodi.config.OodiConfig.java

@Bean
public RestTemplate oodiRestTemplate() {
    final MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter(
            objectMapper());/*from   w  w w .  j a  v a  2  s. com*/

    RestTemplate restTemplate = new RestTemplate(Collections.singletonList(converter));
    restTemplate.setInterceptors(newArrayList(new LoggingInterceptor(), new RequestTimingInterceptor()));
    if (useClientCert()) {
        final HttpClient client = HttpClients.custom().setSSLContext(sslContext()).build();
        restTemplate.setRequestFactory(new HttpComponentsClientHttpRequestFactory(client));
    }
    return restTemplate;
}

From source file:org.kaaproject.kaa.server.appenders.rest.appender.RestLogAppender.java

@Override
protected void initFromConfiguration(LogAppenderDto appender, RestConfig configuration) {
    this.configuration = configuration;
    this.executor = Executors.newFixedThreadPool(configuration.getConnectionPoolSize());
    target = new HttpHost(configuration.getHost(), configuration.getPort(),
            configuration.getSsl() ? "https" : "http");
    HttpClientBuilder builder = HttpClients.custom();
    if (configuration.getUsername() != null && configuration.getPassword() != null) {
        LOG.info("Adding basic auth credentials provider");
        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(new AuthScope(target.getHostName(), target.getPort()),
                new UsernamePasswordCredentials(configuration.getUsername(), configuration.getPassword()));
        builder.setDefaultCredentialsProvider(credsProvider);
    }//from w  w  w  .j ava  2  s  . com
    if (!configuration.getVerifySslCert()) {
        LOG.info("Adding trustful ssl context");
        SSLContextBuilder sslBuilder = new SSLContextBuilder();
        try {
            sslBuilder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
            SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslBuilder.build());
            builder.setSSLSocketFactory(sslsf);
        } catch (NoSuchAlgorithmException | KeyStoreException | KeyManagementException ex) {
            LOG.error("Failed to init socket factory {}", ex.getMessage(), ex);
        }
    }
    PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
    cm.setDefaultMaxPerRoute(configuration.getConnectionPoolSize());
    cm.setMaxTotal(configuration.getConnectionPoolSize());
    builder.setConnectionManager(cm);
    this.client = builder.build();
}

From source file:de.vanita5.twittnuker.util.net.TwidereHttpClientImpl.java

public TwidereHttpClientImpl(final Context context, final HttpClientConfiguration conf) {
    this.conf = conf;
    final HttpClientBuilder clientBuilder = HttpClients.custom();
    final LayeredConnectionSocketFactory factory = TwidereSSLSocketFactory.getSocketFactory(context,
            conf.isSSLErrorIgnored());/*from www .  j a  v a 2  s .c  o m*/
    clientBuilder.setSSLSocketFactory(factory);
    final RequestConfig.Builder requestConfigBuilder = RequestConfig.custom();
    requestConfigBuilder.setConnectionRequestTimeout(conf.getHttpConnectionTimeout());
    requestConfigBuilder.setConnectTimeout(conf.getHttpConnectionTimeout());
    requestConfigBuilder.setSocketTimeout(conf.getHttpReadTimeout());
    requestConfigBuilder.setRedirectsEnabled(false);
    clientBuilder.setDefaultRequestConfig(requestConfigBuilder.build());
    if (conf.isProxyConfigured()) {
        final HttpHost proxy = new HttpHost(conf.getHttpProxyHost(), conf.getHttpProxyPort());
        clientBuilder.setProxy(proxy);
        if (!TextUtils.isEmpty(conf.getHttpProxyUser())) {
            if (logger.isDebugEnabled()) {
                logger.debug("Proxy AuthUser: " + conf.getHttpProxyUser());
                logger.debug(
                        "Proxy AuthPassword: " + InternalStringUtil.maskString(conf.getHttpProxyPassword()));
            }
            final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
            credentialsProvider.setCredentials(new AuthScope(conf.getHttpProxyHost(), conf.getHttpProxyPort()),
                    new UsernamePasswordCredentials(conf.getHttpProxyUser(), conf.getHttpProxyPassword()));
            clientBuilder.setDefaultCredentialsProvider(credentialsProvider);
        }
    }
    client = clientBuilder.build();
}