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:io.github.jonestimd.neo4j.client.http.ApacheHttpDriver.java

private static CloseableHttpClient createClient(CredentialsProvider credentialsProvider) {
    return HttpClients.custom().setDefaultCredentialsProvider(credentialsProvider).build();
}

From source file:com.ibm.CloudResourceBundle.java

private static Rows getServerResponse(CloudDataConnection connect) throws Exception {
    Rows rows = null;//from ww w .  j av a  2s.c om

    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(new AuthScope("provide.castiron.com", 443),
            new UsernamePasswordCredentials(connect.getUserid(), connect.getPassword()));
    CloseableHttpClient httpclient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build();

    try {
        // Call the service and get all the strings for all the languages
        HttpGet httpget = new HttpGet(connect.getURL());
        httpget.addHeader("API_SECRET", connect.getSecret());
        CloseableHttpResponse response = httpclient.execute(httpget);

        try {
            InputStream in = response.getEntity().getContent();
            ObjectMapper mapper = new ObjectMapper();
            rows = mapper.readValue(new InputStreamReader(in, "UTF-8"), Rows.class);
            EntityUtils.consume(response.getEntity());
        } finally {
            response.close();
        }
    } finally {
        httpclient.close();
    }
    return rows;
}

From source file:qhindex.servercomm.ServerDataCache.java

public JSONObject sendRequest(JSONObject data, String url, boolean sentAdminNotification) {
    JSONObject obj = new JSONObject();

    final RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(AppHelper.connectionTimeOut)
            .setConnectionRequestTimeout(AppHelper.connectionTimeOut)
            .setSocketTimeout(AppHelper.connectionTimeOut).setStaleConnectionCheckEnabled(true).build();
    final CloseableHttpClient httpclient = HttpClients.custom().setDefaultRequestConfig(requestConfig).build();
    HttpPost httpPost = new HttpPost(url);

    String dataStr = data.toJSONString();
    dataStr = dataStr.replaceAll("null", "\"\"");

    if (sentAdminNotification == true) {
        try {/*from  w  w  w.  j  a v a2 s  .co  m*/
            AdminMail adminMail = new AdminMail();
            adminMail.sendMailToAdmin("Data to send to the server.", dataStr);
        } catch (Exception ex) { // Catch any problem during this step and continue 
            Debug.print("Could not send admin notification e-mail: " + ex);
        }
    }
    Debug.print("DATA REQUEST: " + dataStr);
    StringEntity jsonData = new StringEntity(dataStr, ContentType.create("plain/text", Consts.UTF_8));
    jsonData.setChunked(true);
    httpPost.addHeader("content-type", "application/json");
    httpPost.addHeader("accept", "application/json");
    httpPost.setEntity(jsonData);

    try (CloseableHttpResponse response = httpclient.execute(httpPost)) {
        StatusLine statusLine = response.getStatusLine();
        if (statusLine.getStatusCode() >= 300) {
            Debug.print("Exception while sending http request: " + statusLine.getStatusCode() + " : "
                    + statusLine.getReasonPhrase());
            resultsMsg += "Exception while sending http request: " + statusLine.getStatusCode() + " : "
                    + statusLine.getReasonPhrase() + "\n";
        }
        BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent())));
        String output = new String();
        String line;
        while ((line = br.readLine()) != null) {
            output += line;
        }
        output = output.substring(output.indexOf('{'));
        try {
            obj = (JSONObject) new JSONParser().parse(output);
        } catch (ParseException pEx) {
            Debug.print(
                    "Could not parse internet response. It is possible the cache server fail to deliver the content: "
                            + pEx.toString());
            resultsMsg += "Could not parse internet response. It is possible the cache server fail to deliver the content.\n";
        }
    } catch (IOException ioEx) {
        Debug.print("Could not handle the internet request: " + ioEx.toString());
        resultsMsg += "Could not handle the internet request.\n";
    }
    return obj;
}

From source file:org.wildfly.swarm.https.test.HttpsTest.java

@Test
@RunAsClient//w ww. j a  v  a  2 s. c  o m
public void hello() throws IOException, GeneralSecurityException {
    SSLContext sslContext = SSLContexts.custom().loadTrustMaterial((TrustStrategy) (chain, authType) -> true)
            .build();
    try (CloseableHttpClient httpClient = HttpClients.custom().setSSLContext(sslContext).build()) {

        String response = Executor.newInstance(httpClient).execute(Request.Get("https://localhost:8443/"))
                .returnContent().asString();
        assertThat(response).contains("Hello on port 8443, secure: true");
    }
}

From source file:cf.spring.servicebroker.AbstractServiceBrokerTest.java

protected CloseableHttpClient buildAuthenticatingClient() {
    return HttpClients.custom().setDefaultCredentialsProvider(credentials()).build();
}

From source file:edu.kit.dama.rest.dataorganization.services.impl.util.HttpDownloadHandler.java

@Override
public Response prepareStream(URL pUrl) throws IOException {
    try {/*from   ww w. j  a v  a2 s  .  c  om*/
        final CloseableHttpClient httpclient = HttpClients.custom()
                .setRedirectStrategy(new LaxRedirectStrategy()) // adds HTTP REDIRECT support to GET and POST methods 
                .build();

        HttpGet httpget = new HttpGet(pUrl.toURI());

        final CloseableHttpResponse response = httpclient.execute(httpget);

        HttpEntity entity = response.getEntity();
        String contentType = entity.getContentType().getValue();
        if (contentType == null) {
            contentType = MediaType.APPLICATION_OCTET_STREAM;
        }

        LOGGER.debug("Using content type '{}' to stream URL content to client.", contentType);
        final InputStream is = entity.getContent();

        final StreamingOutput stream = new StreamingOutput() {
            @Override
            public void write(OutputStream os) throws IOException, WebApplicationException {
                try {
                    byte[] data = new byte[1024];
                    int bytesRead;
                    while ((bytesRead = is.read(data)) != -1) {
                        os.write(data, 0, bytesRead);
                    }
                } finally {
                    response.close();
                    httpclient.close();
                }
            }
        };
        return Response.ok(stream, contentType).build();
    } catch (URISyntaxException ex) {
        throw new IOException("Failed to prepare download stream for URL " + pUrl, ex);
    }
}

From source file:com.anjlab.logback.hipchat.HipChatRoom.java

public HipChatRoom(String room, String apiKey) {
    PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();

    closeableHttpClient = HttpClients.custom().setConnectionManager(cm).build();

    gson = new Gson();

    roomUri = "https://api.hipchat.com/v2/room/" + room + "/notification";
    authorizationHeader = new BasicHeader(HttpHeaders.AUTHORIZATION, "Bearer " + apiKey);
    contentTypeHeader = new BasicHeader(HttpHeaders.CONTENT_TYPE, "application/json");
}

From source file:org.jmonkey.external.bintray.BintrayApiClient.java

private CloseableHttpClient createClient() {

    return HttpClients.custom().setDefaultCookieStore(new BasicCookieStore()).setUserAgent(userAgent)
            .setRedirectStrategy(new LaxRedirectStrategy()).build();
}

From source file:org.alfresco.provision.BMService.java

public BMService(String hostname) {
    this.hostname = hostname;
    HttpClientConnectionManager poolingConnManager = new PoolingHttpClientConnectionManager();
    this.client = HttpClients.custom().setConnectionManager(poolingConnManager).build();
}

From source file:zz.pseas.ghost.client.ClientFactory.java

public static CloseableHttpClient getNewClient() {
    try {//from  w  w  w.j a  v  a 2 s .c  o  m
        SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, new TrustStrategy() {
            public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
                return true;
            }
        }).build();

        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext);
        Registry<ConnectionSocketFactory> reg = RegistryBuilder.<ConnectionSocketFactory>create()
                .register("http", PlainConnectionSocketFactory.getSocketFactory()).register("https", sslsf)
                .build();
        PoolingHttpClientConnectionManager connMgr = new PoolingHttpClientConnectionManager(reg);

        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(10 * 60 * 1000)
                .setConnectionRequestTimeout(10 * 60 * 1000).setConnectionRequestTimeout(10 * 60 * 1000)
                .build();

        CloseableHttpClient client = HttpClients.custom().setDefaultRequestConfig(requestConfig)
                .setConnectionManager(connMgr).build();
        return client;
    } catch (Exception e) {
        return null;
    }
}