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:nl.eveoh.mytimetable.apiclient.service.MyTimetableHttpClientBuilderImpl.java

public CloseableHttpClient build(Configuration configuration) {
    Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
            .register("http", new PlainConnectionSocketFactory())
            .register("https", createSslSocketFactory(configuration)).build();

    // Create the Connection manager.
    PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(registry);
    connectionManager.setMaxTotal(configuration.getApiMaxConnections());
    connectionManager.setDefaultMaxPerRoute(configuration.getApiMaxConnections());

    // Create the HttpClient.
    return HttpClients.custom().setConnectionManager(connectionManager).build();
}

From source file:comsat.sample.tomcat.SampleTomcatSslApplicationTests.java

@Test
public void testHome() throws Exception {
    SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(
            new SSLContextBuilder().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build());

    HttpClient httpClient = HttpClients.custom().setSSLSocketFactory(socketFactory).build();

    TestRestTemplate testRestTemplate = new TestRestTemplate();
    ((HttpComponentsClientHttpRequestFactory) testRestTemplate.getRequestFactory()).setHttpClient(httpClient);
    ResponseEntity<String> entity = testRestTemplate.getForEntity("https://localhost:" + this.port,
            String.class);
    assertEquals(HttpStatus.OK, entity.getStatusCode());
    assertEquals("Hello, world", entity.getBody());
}

From source file:com.simple.weixin.refund.ClientCustomSSL.java

public static String doRefund(String password, String keyStrore, String url, String data) throws Exception {
    /**/*from  w  ww.  j av a  2  s  .  c om*/
     * ?PKCS12? ?-- API 
     */

    KeyStore keyStore = KeyStore.getInstance("PKCS12");
    FileInputStream instream = new FileInputStream(new File(keyStrore));//P12
    try {
        /**
         * ?
         * */
        keyStore.load(instream, password.toCharArray());//?..MCHID
    } finally {
        instream.close();
    }

    // Trust own CA and all self-signed certs
    /**
    * ?
    * */
    SSLContext sslcontext = SSLContexts.custom().loadKeyMaterial(keyStore, password.toCharArray())//?  
            .build();
    // Allow TLSv1 protocol only
    SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new String[] { "TLSv1" },
            null, SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
    CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
    try {
        HttpPost httpost = new HttpPost(url); // ??
        httpost.addHeader("Connection", "keep-alive");
        httpost.addHeader("Accept", "*/*");
        httpost.addHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
        httpost.addHeader("Host", "api.mch.weixin.qq.com");
        httpost.addHeader("X-Requested-With", "XMLHttpRequest");
        httpost.addHeader("Cache-Control", "max-age=0");
        httpost.addHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0) ");
        httpost.setEntity(new StringEntity(data, "UTF-8"));
        CloseableHttpResponse response = httpclient.execute(httpost);
        try {
            HttpEntity entity = response.getEntity();

            String jsonStr = EntityUtils.toString(response.getEntity(), "UTF-8");
            EntityUtils.consume(entity);
            return jsonStr;
        } finally {
            response.close();
        }
    } finally {
        httpclient.close();
    }
}

From source file:ok.MyService2.java

@Override
protected Task<BlockingQueue> createTask() {
    final Task<BlockingQueue> task;
    task = new Task<BlockingQueue>() {

        @Override// w  w  w . j av  a  2 s  . c om
        protected BlockingQueue call() throws Exception {
            BlockingQueue result = new LinkedBlockingQueue<String>();

            PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
            cm.setMaxTotal(100);

            CloseableHttpClient httpclient = HttpClients.custom().setConnectionManager(cm).build();
            try {
                ExecutorService executor = Executors.newFixedThreadPool(sites.size());
                List<Future<String>> results = new ArrayList<Future<String>>();
                for (int i = 0; i < sites.size(); i++) {
                    HttpGet httpget = new HttpGet(sites.get(i));
                    Callable worker = new MyCallable(httpclient, httpget);
                    Future<String> res = executor.submit(worker);
                    results.add(res);
                    // String url = hostList[i];
                    //   Runnable worker = new MyRunnable(url);
                    //   executor.execute(worker);
                    //   executor.submit(null);

                }
                executor.shutdown();
                // Wait until all threads are finish
                //                   while (!executor.isTerminated()) {
                //
                //                   }
                for (Future<String> element : results) {
                    result.add(element.get());
                }
                System.out.println("\nFinished all threads");

            } finally {
                httpclient.close();
            }
            return result;
        }

    };
    return task;
}

From source file:org.cee.net.impl.DefaultHttpClientFactory.java

@Override
public HttpClient createHttpClient() {
    return HttpClients.custom().setConnectionManager(connectionManager)
            .setRoutePlanner(new SystemDefaultRoutePlanner(ProxySelector.getDefault()))
            .addInterceptorFirst(new RedirectHttpResponseInterceptor()).build();
}

From source file:com.huotu.mallduobao.common.thirdparty.ClientCustomSSL.java

public static String doRefund(String url, String data, String celPath, String celPassword) throws Exception {
    /**/*from   ww  w. j  av  a2  s . co  m*/
     * ?PKCS12? ?-- API 
     */

    KeyStore keyStore = KeyStore.getInstance("PKCS12");
    FileInputStream instream = new FileInputStream(new File(celPath));//P12
    try {
        /**
         * ?
         * */
        keyStore.load(instream, celPassword.toCharArray());//?..MCHID
    } finally {
        instream.close();
    }

    // Trust own CA and all self-signed certs
    /**
    * ?
    * */
    SSLContext sslcontext = SSLContexts.custom().loadKeyMaterial(keyStore, celPassword.toCharArray())//?
            .build();
    // Allow TLSv1 protocol only
    SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new String[] { "TLSv1" },
            null, SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
    CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
    try {
        HttpPost httpost = new HttpPost(url); // ??
        httpost.addHeader("Connection", "keep-alive");
        httpost.addHeader("Accept", "*/*");
        httpost.addHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
        httpost.addHeader("Host", "api.mch.weixin.qq.com");
        httpost.addHeader("X-Requested-With", "XMLHttpRequest");
        httpost.addHeader("Cache-Control", "max-age=0");
        httpost.addHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0) ");
        httpost.setEntity(new StringEntity(data, "UTF-8"));
        CloseableHttpResponse response = httpclient.execute(httpost);
        try {
            HttpEntity entity = response.getEntity();

            String jsonStr = EntityUtils.toString(response.getEntity(), "UTF-8");
            EntityUtils.consume(entity);
            return jsonStr;
        } finally {
            response.close();
        }
    } finally {
        httpclient.close();
    }
}

From source file:sample.tomcat.ssl.SampleTomcatSslApplicationTests.java

@Test
public void testHome() throws Exception {
    SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(
            new SSLContextBuilder().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build());

    HttpClient httpClient = HttpClients.custom().setSSLSocketFactory(socketFactory).build();

    TestRestTemplate testRestTemplate = new TestRestTemplate();
    ((HttpComponentsClientHttpRequestFactory) testRestTemplate.getRequestFactory()).setHttpClient(httpClient);
    ResponseEntity<String> entity = testRestTemplate.getForEntity("https://localhost:" + this.port,
            String.class);
    assertThat(entity.getStatusCode()).isEqualTo(HttpStatus.OK);
    assertThat(entity.getBody()).isEqualTo("Hello, world");
}

From source file:com.github.caldav4j.BaseTestCase.java

public static HttpClient createHttpClient(CaldavCredential caldavCredential) {
    // HttpClient 4 requires a Cred providers, to be added during creation of client
    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(AuthScope.ANY,
            new UsernamePasswordCredentials(caldavCredential.user, caldavCredential.password));

    return HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build();
}

From source file:nl.b3p.viewer.admin.ViewerAdminLockoutIntegrationTest.java

/**
 * initialize http client./*from   ww  w  .  j a  va2 s  . c o m*/
 */
@BeforeClass
public static void setupClient() {
    //client = HttpClientBuilder.create().build();
    client = HttpClients.custom().useSystemProperties().setUserAgent("brmo integration test")
            .setRedirectStrategy(new LaxRedirectStrategy()).setDefaultCookieStore(new BasicCookieStore())
            .build();
}

From source file:com.microsoft.applicationinsights.internal.channel.common.ApacheSender43.java

public ApacheSender43() {
    PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
    cm.setMaxTotal(DEFAULT_MAX_TOTAL_CONNECTIONS);
    cm.setDefaultMaxPerRoute(DEFAULT_MAX_CONNECTIONS_PER_ROUTE);

    httpClient = HttpClients.custom().setConnectionManager(cm).build();
}