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.redhat.developers.msa.api_gateway.GenericFeignClient.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  va2  s . com
 * 
 * @param - The original ServerSpan
 * 
 * @return The feign pointing to the service URL and with Hystrix fallback.
 */
protected T createFeign(ServerSpan serverSpan) {
    final CloseableHttpClient httpclient = HttpClients.custom()
            .addInterceptorFirst(new BraveHttpRequestInterceptor(brave.clientRequestInterceptor(),
                    new DefaultSpanNameProvider()))
            .addInterceptorFirst(new BraveHttpResponseInterceptor(brave.clientResponseInterceptor())).build();
    String url = String.format("http://%s:8080/", serviceName);
    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).target(classType, url, fallBack);
}

From source file:org.codice.alliance.nsili.endpoint.requests.FtpDestinationSink.java

@Override
public void writeFile(InputStream fileData, long size, String name, String contentType,
        List<Metacard> metacards) throws IOException {
    CloseableHttpClient httpClient = null;
    String urlPath = protocol + "://" + fileLocation.host_name + ":" + port + "/" + fileLocation.path_name + "/"
            + name;/*w  w w. j  a v  a  2  s  .  c o m*/

    LOGGER.debug("Writing ordered file to URL: {}", urlPath);

    try {
        HttpPut putMethod = new HttpPut(urlPath);
        putMethod.addHeader(HTTP.CONTENT_TYPE, contentType);
        HttpEntity httpEntity = new InputStreamEntity(fileData, size);
        putMethod.setEntity(httpEntity);

        if (StringUtils.isNotEmpty(fileLocation.user_name) && fileLocation.password != null) {
            CredentialsProvider credsProvider = new BasicCredentialsProvider();
            credsProvider.setCredentials(new AuthScope(fileLocation.host_name, port),
                    new UsernamePasswordCredentials(fileLocation.user_name, fileLocation.password));
            httpClient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build();
        } else {
            httpClient = HttpClients.createDefault();
        }

        httpClient.execute(putMethod);
        fileData.close();
        putMethod.releaseConnection();
    } finally {
        if (httpClient != null) {
            httpClient.close();
        }
    }
}

From source file:com.kms.core.io.HttpUtil_In.java

public static CloseableHttpClient getHttpClient(final String SoeID, final String Password, final int type) {
    CloseableHttpClient httpclient;/*from   w w  w. ja v a2s. c o m*/

    // Auth Scheme 
    final Registry<AuthSchemeProvider> authSchemeRegistry = RegistryBuilder.<AuthSchemeProvider>create()
            .register(AuthSchemes.NTLM, new NTLMSchemeFactory())
            .register(AuthSchemes.BASIC, new BasicSchemeFactory())
            .register(AuthSchemes.DIGEST, new DigestSchemeFactory())
            .register(AuthSchemes.SPNEGO, new SPNegoSchemeFactory())
            .register(AuthSchemes.KERBEROS, new KerberosSchemeFactory()).build();

    // NTLM  
    final CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT), //AuthScope("localhost", 8080),
            new NTCredentials(SoeID, Password, "dummy", "APAC"));
    //new NTCredentials( SoeID, Password,"APACKR081WV058", "APAC" ));

    // ------------- cookie start ------------------------
    // Auction   
    // Create a local instance of cookie store
    final CookieStore cookieStore = new BasicCookieStore();

    //       Cookie  .
    final BasicClientCookie cookie = new BasicClientCookie("songdal_view", "YES");
    cookie.setVersion(0);
    cookie.setDomain(".scourt.go.kr");
    cookie.setPath("/");
    cookieStore.addCookie(cookie);

    // ------------- cookie end ------------------------

    if (type == 0) // TYPE.AuctionInput
    {
        // HTTP Client 
        httpclient = HttpClients.custom().setDefaultAuthSchemeRegistry(authSchemeRegistry)
                .setDefaultCredentialsProvider(credsProvider).build();
    } else // SagunInput
    {
        // HTTP Client 
        httpclient = HttpClients.custom().setDefaultAuthSchemeRegistry(authSchemeRegistry)
                .setDefaultCredentialsProvider(credsProvider).setDefaultCookieStore(cookieStore).build();
    }

    return httpclient;
}

From source file:net.siegmar.japtproxy.fetcher.HttpClientConfigurer.java

public CloseableHttpClient build() throws InitializationException {
    final PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager();
    connectionManager.setMaxTotal(MAX_CONNECTIONS);
    connectionManager.setDefaultMaxPerRoute(MAX_CONNECTIONS);

    final RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(connectTimeout)
            .setSocketTimeout(socketTimeout).build();

    final HttpClientBuilder httpClientBuilder = HttpClients.custom().setConnectionManager(connectionManager)
            .setDefaultRequestConfig(requestConfig);

    if (configuration.getHttpProxy() != null) {
        configureProxy(httpClientBuilder, configuration.getHttpProxy());
    }//  w w w .ja v a2  s  .c  om

    return httpClientBuilder.build();
}

From source file:org.frontcache.agent.FrontCacheAgent.java

public FrontCacheAgent(String frontcacheURL) {
    final RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(10000).setConnectTimeout(3000)
            .setCookieSpec(CookieSpecs.IGNORE_COOKIES).build();

    ConnectionKeepAliveStrategy keepAliveStrategy = new ConnectionKeepAliveStrategy() {
        @Override//from w  w w .  ja v  a2 s.co m
        public long getKeepAliveDuration(HttpResponse response, HttpContext context) {
            HeaderElementIterator it = new BasicHeaderElementIterator(
                    response.headerIterator(HTTP.CONN_KEEP_ALIVE));
            while (it.hasNext()) {
                HeaderElement he = it.nextElement();
                String param = he.getName();
                String value = he.getValue();
                if (value != null && param.equalsIgnoreCase("timeout")) {
                    return Long.parseLong(value) * 1000;
                }
            }
            return 10 * 1000;
        }
    };

    client = HttpClients.custom().setDefaultRequestConfig(requestConfig)
            .setRetryHandler(new DefaultHttpRequestRetryHandler(0, false))
            .setKeepAliveStrategy(keepAliveStrategy).setRedirectStrategy(new RedirectStrategy() {
                @Override
                public boolean isRedirected(HttpRequest request, HttpResponse response, HttpContext context)
                        throws ProtocolException {
                    return false;
                }

                @Override
                public HttpUriRequest getRedirect(HttpRequest request, HttpResponse response,
                        HttpContext context) throws ProtocolException {
                    return null;
                }
            }).build();

    this.frontCacheURL = frontcacheURL;

    if (frontcacheURL.endsWith("/"))
        this.frontCacheURI = frontcacheURL + IO_URI;
    else
        this.frontCacheURI = frontcacheURL + "/" + IO_URI;
}

From source file:org.miloss.fgsms.presentation.StatusHelper.java

/**
 * determines if an fgsms service is currently accessible. not for use
 * with other services./* ww  w  .j a va 2s  .  co  m*/
 *
 * @param endpoint
 * @return
 */
public String sendGetRequest(String endpoint) {
    //   String result = null;
    if (endpoint.startsWith("http")) {
        // Send a GET request to the servlet
        try {

            URL url = new URL(endpoint);
            int port = url.getPort();
            if (port <= 0) {
                if (endpoint.startsWith("https:")) {
                    port = 443;
                } else {
                    port = 80;
                }
            }

            HttpClientBuilder create = HttpClients.custom();

            if (mode == org.miloss.fgsms.common.Constants.AuthMode.UsernamePassword) {
                CredentialsProvider credsProvider = new BasicCredentialsProvider();
                credsProvider.setCredentials(new AuthScope(url.getHost(), port),
                        new UsernamePasswordCredentials(username, Utility.DE(password)));
                create.setDefaultCredentialsProvider(credsProvider);
                ;

            }
            CloseableHttpClient c = create.build();

            CloseableHttpResponse response = c.execute(new HttpHost(url.getHost(), port),
                    new HttpGet(endpoint));

            c.close();
            int status = response.getStatusLine().getStatusCode();
            if (status == 200) {
                return "OK";
            }
            return String.valueOf(status);

        } catch (Exception ex) {
            Logger.getLogger(Helper.class).log(Level.WARN,
                    "error fetching http doc from " + endpoint + ex.getLocalizedMessage());
            return "offline";
        }
    } else {
        return "undeterminable";
    }
}

From source file:no.kantega.commons.util.XMLHelper.java

private static CloseableHttpClient getHttpClient() {
    return HttpClients.custom().setDefaultRequestConfig(RequestConfig.custom().setRedirectsEnabled(true)
            .setConnectTimeout(10000).setSocketTimeout(10000).setConnectionRequestTimeout(10000).build())
            .build();//w w  w .  j av a  2s . co m
}

From source file:org.jboss.as.test.integration.management.http.XCorrelationIdTestCase.java

@Before
public void before() throws Exception {

    this.url = new URL("http", managementClient.getMgmtAddress(), MGMT_PORT, MGMT_CTX);
    this.httpContext = new BasicHttpContext();
    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(new AuthScope(url.getHost(), url.getPort()),
            new UsernamePasswordCredentials(Authentication.USERNAME, Authentication.PASSWORD));

    this.httpClient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build();
}

From source file:io.apicurio.hub.api.security.KeycloakLinkedAccountsProvider.java

@PostConstruct
protected void postConstruct() {
    try {//from   www . j  a  v a2 s. c om
        if (config.isDisableKeycloakTrustManager()) {
            SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, new TrustSelfSignedStrategy())
                    .build();
            SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext,
                    NoopHostnameVerifier.INSTANCE);
            httpClient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
        } else {
            httpClient = HttpClients.createSystem();
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}