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.gogh.plugin.translator.TranslatorUtil.java

public static CloseableHttpClient createClient() {
    HttpClientBuilder builder = HttpClients.custom();

    return builder.setDefaultRequestConfig(RequestConfig.custom().setSocketTimeout(5000).setConnectTimeout(5000)
            .setConnectionRequestTimeout(5000).build()).build();
}

From source file:com.world.watch.worldwatchcron.util.PushToUser.java

public static void push(List<String> data, String userId) {
    try {/* w w  w  .  j  ava 2s .  c o  m*/
        InputStream jsonStream = PushToUser.class.getResourceAsStream("/parsePush.json");
        ObjectMapper mapper = new ObjectMapper();
        PushData push = mapper.readValue(jsonStream, PushData.class);
        push.getWhere().setUsername(userId);
        push.getData().setKeywords(data);
        String json = mapper.writeValueAsString(push);

        HttpClient httpClient = HttpClients.custom().setDefaultRequestConfig(RequestConfig.custom().build())
                .build();
        HttpPost post = new HttpPost(URL);
        post.setHeader("X-Parse-Application-Id", "WhqWj009luOxOtIH3rM9iWJICLdf0NKbgqdaui8Q");
        post.setHeader("X-Parse-REST-API-Key", "lThhKObAz1Tkt092Cl1HeZv4KLUsdATvscOaGN2y");
        post.setHeader("Content-Type", "application/json");
        logger.debug("JSON to push {}", json.toString());
        StringEntity strEntity = new StringEntity(json);
        post.setEntity(strEntity);
        httpClient.execute(post);
        logger.debug("Pushed {} to userId {}", data.toString(), userId);
    } catch (Exception ex) {
        logger.error("Push Failed for {} ", userId, ex);
    }

}

From source file:com.calmio.calm.integration.Helpers.HTTPHandler.java

public static HTTPResponseData sendGet(String url, String username, String pwd) throws Exception {
    CloseableHttpClient client = HttpClients.custom()
            .setDefaultCredentialsProvider(getCredentialsProvider(url, username, pwd)).build();

    int responseCode = 0;
    StringBuffer respo = null;/*from   w  w  w.  j  ava  2  s  .  c  o m*/
    String userPassword = username + ":" + pwd;
    //        String encoding = Base64.getEncoder().encodeToString(userPassword.getBytes());
    String encoding = Base64.encodeBase64String(userPassword.getBytes());

    try {
        HttpGet request = new HttpGet(url);
        request.addHeader("Authorization", "Basic " + encoding);
        request.addHeader("User-Agent", USER_AGENT);
        System.out.println("Executing request " + request.getRequestLine());
        CloseableHttpResponse response = client.execute(request);
        try {
            responseCode = response.getStatusLine().getStatusCode();
            System.out.println("\nSending 'GET' request to URL : " + url);
            System.out.println("Response Code : " + responseCode);
            BufferedReader in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
            respo = new StringBuffer();
            String inputLine;
            while ((inputLine = in.readLine()) != null) {
                respo.append(inputLine);
            }
        } finally {
            response.close();
        }
    } finally {
        client.close();
    }

    HTTPResponseData result = new HTTPResponseData(responseCode, ((respo == null) ? "" : respo.toString()));
    System.out.println(result.getStatusCode() + "/n" + result.getBody());
    return result;
}

From source file:costumetrade.common.util.HttpClientUtils.java

public static String doPost(String url, HttpEntity httpEntity) {

    logger.info("?{}....", url);

    try (CloseableHttpClient httpclient = HttpClients.custom().build();) {
        HttpPost request = new HttpPost(url);
        request.setEntity(httpEntity);//from   ww w.  ja va 2  s  . co m
        try (CloseableHttpResponse response = httpclient.execute(request);) {
            int statusCode = response.getStatusLine().getStatusCode();
            logger.info("?{}???{}", url, statusCode);
            if (HttpStatus.SC_OK == statusCode) {
                return IOUtils.toString(response.getEntity().getContent(), StandardCharsets.UTF_8.name());
            }
            throw new RuntimeException(String.format("?%s???%s", url, statusCode));
        }
    } catch (Exception e) {
        throw new RuntimeException(String.format("%s", url), e);
    }
}

From source file:com.srotya.sidewinder.cluster.Utils.java

/**
 * Build a {@link CloseableHttpClient}//  w w  w . ja va  2  s .  c o  m
 * 
 * @param baseURL
 * @param connectTimeout
 * @param requestTimeout
 * @return http client
 * @throws NoSuchAlgorithmException
 * @throws KeyStoreException
 * @throws KeyManagementException
 */
public static CloseableHttpClient buildClient(String baseURL, int connectTimeout, int requestTimeout)
        throws NoSuchAlgorithmException, KeyStoreException, KeyManagementException {
    HttpClientBuilder clientBuilder = HttpClients.custom();
    RequestConfig config = RequestConfig.custom().setConnectTimeout(connectTimeout)
            .setConnectionRequestTimeout(requestTimeout).build();

    return clientBuilder.setDefaultRequestConfig(config).build();
}

From source file:org.openo.nfvo.emsdriver.northbound.client.HttpClientFactory.java

public static CloseableHttpClient getSSLClientFactory() throws Exception {

    SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
        ////w  ww  .ja  v a2 s  . c  om
        public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            return true;
        }
    }).build();
    SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext);
    CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();

    return httpclient;
}

From source file:lh.api.showcase.server.util.HttpClientUtils.java

public static CloseableHttpClient createHttpClient(HasProxySettings proxySetting,
        PoolingHttpClientConnectionManager connectionManager) {
    // http://hc.apache.org/httpcomponents-client-ga/tutorial/html/connmgmt.html#d5e475

    HttpClientBuilder clientBuilder = HttpClients.custom();
    if (proxySetting != null && proxySetting.isActive()) {
        logger.info("Set the http proxy (" + proxySetting.getHost() + ":" + proxySetting.getPort() + ")");
        CredentialsProvider credsProvider = Preconditions.checkNotNull(proxySetting.getCredentialsProvider());
        HttpHost proxy = new HttpHost(proxySetting.getHost(), proxySetting.getPort());
        DefaultProxyRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxy);

        clientBuilder.setRoutePlanner(routePlanner).setDefaultCredentialsProvider(credsProvider);
    }//from   w  w  w. ja  va2 s.  c o m
    if (connectionManager != null) {
        clientBuilder.setConnectionManager(connectionManager);
    }
    return clientBuilder.build();
}

From source file:com.ethercamp.harmony.util.TrustSSL.java

/**
 * Allows server to connect to HTTPS sites.
 *//*from   w  w  w . j  a v a  2s.com*/
public static void apply() {
    // ignore https errors
    SSLContext sslcontext = null;
    try {
        sslcontext = SSLContexts.custom().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build();
    } catch (Exception e) {
        e.printStackTrace();
    }

    SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext);
    CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
    Unirest.setHttpClient(httpclient);
}

From source file:ezbake.crypto.utils.TestExternalHttps.java

private static HttpClient getSSLHttpClient() {
    HttpClient httpClient;//from   ww w  .ja  v  a 2s.co m

    Properties serverProps = new Properties();
    serverProps.setProperty(EzBakePropertyConstants.EZBAKE_CERTIFICATES_DIRECTORY, "src/test/resources");
    serverProps.setProperty(EzBakePropertyConstants.EZBAKE_SECURITY_ID, "appId");
    serverProps.setProperty(EzBakePropertyConstants.EZBAKE_APPLICATION_KEYSTORE_FILE, "keystore.jks");
    serverProps.setProperty(EzBakePropertyConstants.EZBAKE_APPLICATION_KEYSTORE_TYPE, "JKS");
    serverProps.setProperty(EzBakePropertyConstants.EZBAKE_APPLICATION_KEYSTORE_PASS, "password");

    try {
        httpClient = HttpClients.custom().setSslcontext(EzSSL.getSSLContext(serverProps)).build();
    } catch (Exception e) {
        e.printStackTrace();
        throw new RuntimeException("IO Exception reading keystore/truststore file: " + e.getMessage());
    }
    return httpClient;
}

From source file:com.softinstigate.restheart.integrationtest.ContentEncodingIT.java

@BeforeClass
public static void init() throws Exception {
    notDecompressingExecutor = Executor.newInstance(HttpClients.custom().disableContentCompression().build())
            .authPreemptive(new HttpHost("127.0.0.1", 8080, "http"))
            .auth(new HttpHost("127.0.0.1"), "admin", "changeit");
}