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:pl.wavesoftware.wfirma.api.simple.mapper.SimpleGateway.java

private String get(@Nonnull HttpRequest httpRequest) throws WFirmaException {
    httpRequest.setHeader("Accept", "text/xml");
    HttpHost target = getTargetHost();/*  ww w . j a  v  a 2 s .c o  m*/
    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(new AuthScope(target.getHostName(), target.getPort()),
            new UsernamePasswordCredentials(credentials.getConsumerKey(), credentials.getConsumerSecret()));
    try (CloseableHttpClient httpclient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider)
            .build()) {

        // Create AuthCache instance
        AuthCache authCache = new BasicAuthCache();
        // Generate BASIC scheme object and add it to the local
        // auth cache
        BasicScheme basicAuth = new BasicScheme();
        authCache.put(target, basicAuth);

        // Add AuthCache to the execution context
        HttpClientContext localContext = HttpClientContext.create();
        localContext.setAuthCache(authCache);

        try (CloseableHttpResponse response = httpclient.execute(target, httpRequest, localContext)) {
            return getContent(response);
        }
    } catch (IOException ioe) {
        throw new RemoteGatewayException(ioe);
    }
}

From source file:org.jboss.as.test.integration.web.security.jaspi.WebSecurityJaspiTestCase.java

protected void makeCall(String user, String pass, int expectedStatusCode) 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() + "secured/");

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

        StatusLine statusLine = response.getStatusLine();
        if (entity != null) {
            log.trace("Response content length: " + entity.getContentLength());
        }//from ww  w . j a  v  a  2  s  .  com
        assertEquals(expectedStatusCode, statusLine.getStatusCode());
        EntityUtils.consume(entity);
    }
}

From source file:ru.neverdark.yotta.parser.YottaParser.java

private void parse(Array array) {
    final String URL = String.format("http://%s/hierarch.htm", array.getIp());
    final StringBuffer result = new StringBuffer();

    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(new AuthScope(array.getIp(), 80),
            new UsernamePasswordCredentials(array.getUser(), array.getPassword()));
    CloseableHttpClient httpClient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build();
    try {/* w  w w . j  a  v  a 2 s .c o m*/
        HttpGet httpget = new HttpGet(URL);
        CloseableHttpResponse response = httpClient.execute(httpget);
        System.err.printf("%s\t%s\n", array.getIp(), response.getStatusLine());
        try {
            BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

            String line = "";
            while ((line = rd.readLine()) != null) {
                result.append(line);
            }

            Document doc = Jsoup.parse(result.toString());
            Elements tables = doc.getElementsByAttribute("vspace");
            // skip first
            for (int i = 1; i < tables.size(); i++) {
                parseTable(tables.get(i), array.getType());
            }

        } finally {
            response.close();
        }

    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } finally {
        try {
            httpClient.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

}

From source file:com.github.horrorho.liquiddonkey.http.HttpClientFactory.java

public CloseableHttpClient client() {
    logger.trace("<< client()");

    PoolingHttpClientConnectionManager connectionManager = config.isRelaxedSSL()
            ? new PoolingHttpClientConnectionManager(relaxedSocketFactoryRegistry())
            : new PoolingHttpClientConnectionManager();

    connectionManager.setMaxTotal(config.maxConnections());
    connectionManager.setDefaultMaxPerRoute(config.maxConnections());
    connectionManager.setValidateAfterInactivity(config.validateAfterInactivityMs());

    RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(config.timeoutMs())
            .setConnectTimeout(config.timeoutMs()).setSocketTimeout(config.timeoutMs()).build();

    HttpRequestRetryHandler httpRequestRetryHandler = config.isPersistent()
            ? new PersistentHttpRequestRetryHandler(config.retryCount(), config.retryDelayMs(),
                    config.timeoutMs(), true)
            : new DefaultHttpRequestRetryHandler(config.retryCount(), false);

    CloseableHttpClient client = HttpClients.custom().setRetryHandler(httpRequestRetryHandler)
            .setConnectionManager(connectionManager).setDefaultRequestConfig(requestConfig)
            .setUserAgent(config.userAgent()).build();

    logger.trace(">> client()", client);
    return client;
}

From source file:RestApiHttpClient.java

/**
 * Create an new {@link RestApiHttpClient} instance with Endpoint, username and API-Key
 * //from   w  w w .  ja  v a 2 s.  c  o m
 * @param apiEndpoint The Hostname and Api-Endpoint (http://www.example.com/api)
 * @param username Shopware Username
 * @param password Api-Key from User-Administration
 */
public RestApiHttpClient(URL apiEndpoint, String username, String password) {
    this.apiEndpoint = apiEndpoint;

    BasicHttpContext context = new BasicHttpContext();
    this.localContext = HttpClientContext.adapt(context);
    HttpHost target = new HttpHost(this.apiEndpoint.getHost(), -1, this.apiEndpoint.getProtocol());
    this.localContext.setTargetHost(target);

    TargetAuthenticationStrategy authStrat = new TargetAuthenticationStrategy();
    UsernamePasswordCredentials creds = new UsernamePasswordCredentials(username, password);
    BasicCredentialsProvider credsProvider = new BasicCredentialsProvider();
    AuthScope aScope = new AuthScope(target.getHostName(), target.getPort());
    credsProvider.setCredentials(aScope, creds);

    BasicAuthCache authCache = new BasicAuthCache();
    // Digest Authentication
    DigestScheme digestAuth = new DigestScheme(Charset.forName("UTF-8"));
    authCache.put(target, digestAuth);
    this.localContext.setAuthCache(authCache);
    this.localContext.setCredentialsProvider(credsProvider);

    ArrayList<Header> defHeaders = new ArrayList<>();
    defHeaders.add(new BasicHeader(HttpHeaders.ACCEPT, ContentType.APPLICATION_JSON.getMimeType()));
    this.httpclient = HttpClients.custom().useSystemProperties().setTargetAuthenticationStrategy(authStrat)
            .disableRedirectHandling()
            // make Rest-API Endpoint GZIP-Compression enable comment this out
            // Response-Compression is also possible
            .disableContentCompression().setDefaultHeaders(defHeaders)
            .setDefaultCredentialsProvider(credsProvider).build();

}

From source file:com.github.restdriver.clientdriver.integration.SecureClientDriverRuleTest.java

private HttpClient getClient() throws KeyManagementException, NoSuchAlgorithmException, KeyStoreException {
    try {/*ww w .jav  a  2 s .  c  om*/
        // set the test certificate as trusted
        SSLContext context = SSLContexts.custom()
                .loadTrustMaterial(getKeystore(), TrustSelfSignedStrategy.INSTANCE).build();
        return HttpClients.custom().setSSLHostnameVerifier(new NoopHostnameVerifier()).setSSLContext(context)
                .build();
    } catch (Exception e) {
        throw new ClientDriverSetupException("Client could not be created.", e);
    }
}

From source file:com.meltmedia.cadmium.core.github.ApiClient.java

protected HttpClient createHttpClient() {
    HttpClient client = HttpClients.custom()
            .setDefaultSocketConfig(SocketConfig.custom().setSoReuseAddress(true).build()).build();
    return client;
}

From source file:com.intuit.tank.httpclient4.TankHttpClient4.java

/**
 * no-arg constructor for client//from www.  j  a  v a  2s  . c  o m
 */
public TankHttpClient4() {
    try {
        SSLContextBuilder builder = new SSLContextBuilder();
        builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
        sslsf = new SSLConnectionSocketFactory(builder.build(), new HostnameVerifier() {
            @Override
            public boolean verify(String arg0, SSLSession arg1) {
                return true;
            }
        });
    } catch (Exception e) {
        LOG.error("Error setting accept all: " + e, e);
    }

    httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
    requestConfig = RequestConfig.custom().setSocketTimeout(30000).setConnectTimeout(30000)
            .setCircularRedirectsAllowed(true).setAuthenticationEnabled(true).setRedirectsEnabled(true)
            .setMaxRedirects(100).build();

    // Make sure the same context is used to execute logically related
    // requests
    context = HttpClientContext.create();
    context.setCredentialsProvider(new BasicCredentialsProvider());
    context.setCookieStore(new BasicCookieStore());
    context.setRequestConfig(requestConfig);
}

From source file:com.jaeksoft.searchlib.crawler.web.spider.HttpAbstract.java

public HttpAbstract(String userAgent, boolean bFollowRedirect, ProxyHandler proxyHandler) {
    HttpClientBuilder builder = HttpClients.custom();

    redirectStrategy = new DefaultRedirectStrategy();

    if (userAgent != null) {
        userAgent = userAgent.trim();//from  w  w  w .j  av  a  2  s  . c  om
        if (userAgent.length() > 0)
            builder.setUserAgent(userAgent);
        else
            userAgent = null;
    }
    if (!bFollowRedirect)
        builder.disableRedirectHandling();

    this.proxyHandler = proxyHandler;

    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();

    credentialsProvider = new BasicCredentialsProvider();
    builder.setDefaultCredentialsProvider(credentialsProvider);

    cookieStore = new BasicCookieStore();
    builder.setDefaultCookieStore(cookieStore);

    builder.setDefaultCredentialsProvider(credentialsProvider);
    builder.setDefaultAuthSchemeRegistry(authSchemeRegistry);

    httpClient = builder.build();

}