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.mycompany.projecta.JenkinsScraper.java

public String scrape(String urlString, String username, String password)
        throws ClientProtocolException, IOException {
    URI uri = URI.create(urlString);
    HttpHost host = new HttpHost(uri.getHost(), uri.getPort(), uri.getScheme());
    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(new AuthScope(uri.getHost(), uri.getPort()),
            new UsernamePasswordCredentials(username, password));
    // 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(host, basicAuth);//w  w w  .j a  va  2 s  .c o  m
    CloseableHttpClient httpClient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build();
    HttpGet httpGet = new HttpGet(uri);
    // Add AuthCache to the execution context
    HttpClientContext localContext = HttpClientContext.create();
    localContext.setAuthCache(authCache);

    HttpResponse response = httpClient.execute(host, httpGet, localContext);

    String resp = response.toString();

    return EntityUtils.toString(response.getEntity());
}

From source file:com.facebook.presto.jdbc.QueryExecutor.java

private QueryExecutor(String userAgent, ObjectMapper mapper, HttpHost proxy) {
    checkNotNull(userAgent, "userAgent is null");
    checkNotNull(mapper, "mapper is null");

    this.userAgent = userAgent;
    this.mapper = mapper;

    HttpClientBuilder builder = HttpClients.custom();
    HttpAsyncClientBuilder asyncBuilder = HttpAsyncClients.custom();

    if (proxy != null) {
        DefaultProxyRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxy);
        builder.setRoutePlanner(routePlanner);
        asyncBuilder.setRoutePlanner(routePlanner);
    }// ww  w  .  ja v a  2 s . c  o m

    this.httpClient = asyncBuilder.build();
    this.httpClient.start();
}

From source file:com.joken.notice.message.util.HttpRequestHandler.java

/**
 * ??post/*from w w w .j av  a 2 s. c  o  m*/
 * @Auther Hanzibin
 * @date 3:18:48 PM,Mar 11, 2016
 * @return String 
 */
public String sendPostRequest() {
    CloseableHttpResponse httpResponse = null;
    PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager();
    connManager.setMaxTotal(300);
    connManager.setDefaultMaxPerRoute(20);
    if (requestConfig == null) {
        requestConfig = RequestConfig.custom().setConnectionRequestTimeout(10000)
                .setStaleConnectionCheckEnabled(true).setConnectTimeout(10000).setSocketTimeout(10000).build();
    }
    CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(connManager)
            .setDefaultRequestConfig(requestConfig).build();

    HttpPost hp = new HttpPost(url);
    try {
        StringEntity entity = new StringEntity(postData, Charset.forName("UTF-8"));//?    
        entity.setContentEncoding("UTF-8");
        entity.setContentType("application/json");
        hp.setEntity(entity);
        httpResponse = httpClient.execute(hp);
        return EntityUtils.toString(httpResponse.getEntity());
    } catch (Throwable t) {
        t.printStackTrace();
        log.info("??Http" + postData.toString() + "");
    } finally {
        try {
            hp.releaseConnection();
        } catch (Exception e) {
        }
    }
    return null;
}

From source file:io.confluent.support.metrics.utils.WebClientProxyTest.java

@BeforeClass
public static void startProxy() throws Exception {

    int port = PortFactory.findFreePort();
    clientAndProxy = startClientAndProxy(port);
    proxy = new HttpHost("localhost", port);
    // load truststore with MockServer CA
    sslContext = SSLContexts.custom()/*w w  w  . j  a v  a2s. c  o m*/
            .loadTrustMaterial(new File("src/test/resources/truststore.jks"), "changeit".toCharArray()).build();
    httpClientBuilder = HttpClients.custom().setSSLContext(sslContext);
    httpclient = httpClientBuilder.build();

    serverPort = PortFactory.findFreePort();
    clientAndServer = ClientAndServer.startClientAndServer(serverPort);
    clientAndServer.when(new HttpRequest().withMethod("GET")).respond(HttpResponse.response("OK"));
}

From source file:org.apache.jena.jdbc.remote.results.TestRemoteEndpointResultsWithAuth.java

/**
 * Setup for the tests by allocating a Fuseki instance to work with
 * //from w  w  w. j  av  a  2 s. c o  m
 * @throws SQLException
 * @throws IOException
 */
@BeforeClass
public static void setup() throws SQLException, IOException {
    SecurityHandler sh = FusekiTestAuth.makeSimpleSecurityHandler("/*", USER, PASSWORD);
    FusekiTestAuth.setupServer(true, sh);

    BasicCredentialsProvider credsProv = new BasicCredentialsProvider();
    credsProv.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(USER, PASSWORD));
    client = HttpClients.custom().setDefaultCredentialsProvider(credsProv).build();

    connection = new RemoteEndpointConnection(FusekiTestAuth.serviceQuery(), FusekiTestAuth.serviceUpdate(),
            null, null, null, null, client, JenaConnection.DEFAULT_HOLDABILITY, JdbcCompatibility.DEFAULT, null,
            null);
    connection.setJdbcCompatibilityLevel(JdbcCompatibility.HIGH);
}

From source file:com.sh.util.SslHttpClientFactoryBean.java

@Override
public HttpClient getObject() throws Exception {
    KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
    TrustStrategy allTrust = new TrustStrategy() {
        @Override// ww w .j  ava2  s. co  m
        public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            return true;
        }
    };
    SSLContext sslcontext = SSLContexts.custom().useTLS().loadTrustMaterial(trustStore, allTrust).build();
    SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext,
            SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
    return HttpClients.custom().setSSLSocketFactory(sslsf).build();
}

From source file:com.deying.util.weixin.ClientCustomSSL.java

public static String doRefund(String url, String data) throws Exception {
    System.out.println("111111111111111111111111111111111111111111111118 ");
    KeyStore keyStore = KeyStore.getInstance("PKCS12");
    FileInputStream instream = new FileInputStream(new File("E:/apiclient_cert.p12"));//P12
    try {/*from  ww w . j  a va 2 s  .c om*/
        keyStore.load(instream, "1233374102".toCharArray());//?..MCHID
    } finally {
        instream.close();
    }

    // Trust own CA and all self-signed certs
    SSLContext sslcontext = SSLContexts.custom().loadKeyMaterial(keyStore, "1233374102".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:org.exem.flamingo.shared.util.SslHttpClientFactoryBean.java

@Override
public HttpClient getObject() throws Exception {
    KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
    TrustStrategy allTrust = new TrustStrategy() {
        public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            return true;
        }/* w w  w  .j av a  2 s  . c om*/
    };
    SSLContext sslcontext = SSLContexts.custom().useTLS().loadTrustMaterial(trustStore, allTrust).build();
    SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext,
            SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
    return HttpClients.custom().setSSLSocketFactory(sslsf).build();
}

From source file:io.fabric8.elasticsearch.plugin.HttpsProxyClientCertAuthenticatorIntegrationTest.java

@Test
public void testProxyAuthWithSSL() throws Exception {
    SSLContext sslContext = new SSLContextBuilder()
            .loadTrustMaterial(new File(keyStoreFile), keystorePW.toCharArray(), new TrustSelfSignedStrategy())
            .build();/*from  ww w. ja v a2 s.c om*/

    try (CloseableHttpClient httpclient = HttpClients.custom().setSSLContext(sslContext)
            .setSSLHostnameVerifier(new HostnameVerifier() {

                @Override
                public boolean verify(String hostname, SSLSession session) {
                    return true;
                }

            }).build()) {
        Executor ex = Executor.newInstance(httpclient);
        Response response = ex.execute(Request.Get("https://localhost:9200/blahobar.234324234/logs/1")
                .addHeader("Authorization", String.format("Bearer %s", token))
                .addHeader("X-Proxy-Remote-User", proxyUser));
        System.out.println(response.returnContent().asString());
    } catch (Exception e) {
        System.out.println(e);
        fail("Test Failed");
    }
}

From source file:Yak_Hax.Yak_Hax_Mimerme.PostRequest.java

public static String PostBodyRequest(String URL, String JSONRaw, TreeMap<String, String> headers)
        throws IOException {

    HttpPost post = new HttpPost(URL);

    HttpClient httpclient = HttpClients.custom().build();
    post.setEntity(new StringEntity(JSONRaw));
    post.setHeader("Content-Type", "application/json; charset=utf-8");
    for (Map.Entry<String, String> entry : headers.entrySet()) {
        String key = entry.getKey();
        String value = entry.getValue();

        post.setHeader(key, value);/*from ww w .java 2s  .  c o m*/
    }
    HttpResponse response = httpclient.execute(post);

    BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

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