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:au.com.borner.salesforce.client.rest.ConnectionManager.java

public ConnectionManager() {
    loggedIn = false;// w w w  .j  av  a  2  s .  c om
    SSLContext sslContext = SSLContexts.createSystemDefault();
    LayeredConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext);

    PoolingHttpClientConnectionManager pcm = new PoolingHttpClientConnectionManager();
    pcm.setMaxTotal(100);
    pcm.setDefaultMaxPerRoute(50);

    HttpCompressionRequestInterceptor requestInterceptor = new HttpCompressionRequestInterceptor();
    HttpCompressionResponseInterceptor responseInterceptor = new HttpCompressionResponseInterceptor();

    httpClient = HttpClients.custom().setConnectionManager(pcm).setSSLSocketFactory(sslSocketFactory)
            .addInterceptorFirst(requestInterceptor).addInterceptorFirst(responseInterceptor).build();
}

From source file:com.microsoft.azure.hdinsight.spark.jobs.SparkRestUtil.java

public static HttpEntity getEntity(@NotNull IClusterDetail clusterDetail, @NotNull String restUrl)
        throws HDIException, IOException {
    provider.setCredentials(AuthScope.ANY,
            new UsernamePasswordCredentials(clusterDetail.getHttpUserName(), clusterDetail.getHttpPassword()));
    HttpClient client = HttpClients.custom().setDefaultCredentialsProvider(provider).build();
    String url = String.format(SPARK_REST_API_ENDPOINT, clusterDetail.getName(), restUrl);
    HttpGet get = new HttpGet(url);
    HttpResponse response = client.execute(get);
    int code = response.getStatusLine().getStatusCode();
    if (code == HttpStatus.SC_OK || code == HttpStatus.SC_CREATED) {
        return response.getEntity();
    } else {//from  w  w  w.  j a  v a2  s.c om
        throw new HDIException(response.getStatusLine().getReasonPhrase(),
                response.getStatusLine().getStatusCode());
    }
}

From source file:com.ericsson.gerrit.plugins.syncindex.HttpClientProvider.java

@Override
public CloseableHttpClient get() {
    return HttpClients.custom().setSSLSocketFactory(sslSocketFactory)
            .setConnectionManager(customConnectionManager()).setDefaultCredentialsProvider(buildCredentials())
            .setDefaultRequestConfig(customRequestConfig()).setRetryHandler(customRetryHandler())
            .setServiceUnavailableRetryStrategy(customServiceUnavailRetryStrategy()).build();
}

From source file:org.eclipse.vorto.repository.RestClient.java

@SuppressWarnings("restriction")
public Attachment executeGetAttachment(String query) throws ClientProtocolException, IOException {

    CloseableHttpClient client = HttpClients.custom().build();

    HttpUriRequest request = RequestBuilder.get().setConfig(createProxyConfiguration())
            .setUri(createQuery(query)).build();
    return client.execute(request, new ResponseHandler<Attachment>() {

        @Override//from w w  w .  j  a  v a 2 s  .com
        public Attachment handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
            String content_disposition = response.getFirstHeader("Content-Disposition").getValue();
            String filename = content_disposition
                    .substring(content_disposition.indexOf("filename = ") + "filename = ".length());
            long length = response.getEntity().getContentLength();
            String type = response.getEntity().getContentType().toString();
            byte[] content = IOUtils.toByteArray(response.getEntity().getContent());
            return new Attachment(filename, length, type, content);
        }
    });
}

From source file:it.larusba.neo4j.jdbc.http.driver.CypherExecutor.java

/**
 * Default constructor.//w  ww . j a  v  a2 s.  com
 *
 * @param host       Hostname of the Neo4j instance.
 * @param port       HTTP port of the Neo4j instance.
 * @param properties Properties of the url connection.
 * @throws SQLException
 */
public CypherExecutor(String host, Integer port, Properties properties) throws SQLException {
    // Create the http client builder
    HttpClientBuilder builder = HttpClients.custom();
    // Adding authentication to the http client if needed
    if (properties.containsKey("user") && properties.containsKey("password")) {
        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(new AuthScope(host, port), new UsernamePasswordCredentials(
                properties.get("user").toString(), properties.get("password").toString()));
        builder.setDefaultCredentialsProvider(credsProvider);
    }
    // Setting user-agent
    StringBuilder sb = new StringBuilder();
    sb.append("Neo4j JDBC Driver");
    if (properties.containsKey("userAgent")) {
        sb.append(" via ");
        sb.append(properties.getProperty("userAgent"));
    }
    builder.setUserAgent(sb.toString());
    // Create the http client
    this.http = builder.build();

    // Create the url endpoint
    StringBuffer sbEndpoint = new StringBuffer();
    sbEndpoint.append("http://").append(host).append(":").append(port).append("/db/data/transaction");
    this.transactionUrl = sbEndpoint.toString();

    // Setting autocommit
    this.setAutoCommit(Boolean.valueOf(properties.getProperty("autoCommit", "true")));
}

From source file:com.terracotta.nrplugin.rest.nr.MetricReporter.java

@PostConstruct
private void init() {
    RequestConfig defaultRequestConfig = RequestConfig.custom().setConnectTimeout(10000).setSocketTimeout(10000)
            .setConnectionRequestTimeout(5000).setStaleConnectionCheckEnabled(true).build();
    HttpClientBuilder httpClientBuilder = HttpClients.custom().setDefaultRequestConfig(defaultRequestConfig);
    if (useProxy) {
        int parsedProxyPort = 8080;
        try {/*from   ww w.  j  a v  a  2  s.  c om*/
            parsedProxyPort = Integer.parseInt(proxyPort);
        } catch (NumberFormatException e) {
            log.warn("Could not parse the proxyPort. Defaulting to 8080.");
            parsedProxyPort = 8080;
        }

        HttpHost proxy = new HttpHost(proxyHostname, parsedProxyPort, proxyScheme);
        httpClientBuilder.setProxy(proxy);
        log.info("Configuring HttpClient with proxy '" + proxy.toString() + "'");
    }
    httpClient = httpClientBuilder.build();
}

From source file:nya.miku.wishmaster.http.client.ExtendedHttpClient.java

private static HttpClient build(boolean safe, final HttpHost proxy, CookieStore cookieStore) {
    return HttpClients.custom()
            .setDefaultRequestConfig(getDefaultRequestConfigBuilder(HttpConstants.DEFAULT_HTTP_TIMEOUT).build())
            .setUserAgent(HttpConstants.USER_AGENT_STRING).setProxy(proxy).setDefaultCookieStore(cookieStore)
            .setSSLSocketFactory(obtainSSLSocketFactory(safe)).build();
}

From source file:ss.udapi.sdk.services.HttpServices.java

public ServiceRequest getSession(String url, boolean compressionEnabled) throws Exception {

    this.compressionEnabled = compressionEnabled;
    List<RestItem> loginRestItems = null;
    ServiceRequest loginResp = new ServiceRequest();

    CloseableHttpClient httpClient = null;
    try {// w ww .  j a  va 2  s  .co  m

        logger.info("Retrieving connection actions from url: " + url);

        // this is only to check whether the URL format is correct
        new URL(url);

        HttpGet httpGet = new HttpGet(url);
        if (compressionEnabled == true) {
            httpGet.setHeader("Accept-Encoding", "gzip");
        }

        httpClient = HttpClients.custom().setKeepAliveStrategy(requestTimeout).build();
        ResponseHandler<String> responseHandler = getResponseHandler(401);

        // Call the end-point using connectivity details we've prepared above
        // and get the list of end-points we have access to.
        String responseBody = httpClient.execute(httpGet, responseHandler);

        loginRestItems = JsonHelper.toRestItems(responseBody);
        ArrayList<String> names = new ArrayList<String>();
        for (RestItem item : loginRestItems) {
            names.add(item.getName());
        }

        logger.debug("Retrieved connection actions: " + names.toString());

        loginResp.setServiceRestItems(loginRestItems);
        return loginResp;

    } catch (MalformedURLException urlEx) {
        logger.error("malformed URL: " + url);
        throw urlEx;
    } catch (ClientProtocolException protEx) {
        logger.error("Invalid Client Protocol: " + protEx.getCause());
        throw protEx;
    } catch (IOException ioEx) {
        logger.error("Communication error: to URL [" + url + "]");
        throw ioEx;
    } finally {

        try {
            if (httpClient != null)
                httpClient.close();
        } catch (IOException ex) {
            // Can safely be ignored, either the server closed the
            // connection or we didn't open it so there's nothing to do.
        }
    }
}

From source file:com.sumologic.log4j.http.SumoHttpSender.java

public void init() {
    RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(socketTimeout)
            .setConnectTimeout(connectionTimeout).build();

    HttpClientBuilder builder = HttpClients.custom()
            .setConnectionManager(new PoolingHttpClientConnectionManager())
            .setDefaultRequestConfig(requestConfig);

    HttpProxySettingsCreator creator = new HttpProxySettingsCreator(proxySettings);
    creator.configureProxySettings(builder);

    httpClient = builder.build();//from   w  w w . j a v a  2  s  .  c  o m
}

From source file:org.nekorp.workflow.desktop.rest.util.RestTemplateFactory.java

@PostConstruct
public void init() {
    targetHost = new HttpHost(host, port, protocol);
    //connectionPool = new PoolingHttpClientConnectionManager();
    //connectionPool.setDefaultMaxPerRoute(10);
    //connectionPool.setMaxTotal(20);

    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(new AuthScope(targetHost.getHostName(), targetHost.getPort()),
            new UsernamePasswordCredentials(username, password));
    //wildcard ssl certificate
    SSLContext sslContext = SSLContexts.createDefault();
    SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext,
            NoopHostnameVerifier.INSTANCE);

    httpclient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider)
            //.setConnectionManager(connectionPool)
            .setSSLSocketFactory(sslsf).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(targetHost, basicAuth);

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

    HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactoryBasicAuth(
            httpclient, localContext);//  ww  w  .  ja  v a 2  s .c  o m
    this.template = new RestTemplate();
    template.getMessageConverters().add(new BufferedImageHttpMessageConverter());
    template.setRequestFactory(factory);
}