Example usage for org.apache.http.impl.client HttpClientBuilder create

List of usage examples for org.apache.http.impl.client HttpClientBuilder create

Introduction

In this page you can find the example usage for org.apache.http.impl.client HttpClientBuilder create.

Prototype

public static HttpClientBuilder create() 

Source Link

Usage

From source file:org.hawkular.component.pinger.Pinger.java

private CloseableHttpClient getHttpClient(final String url) {
    if (url != null && url.startsWith("https://") && sslContext != null) {
        return HttpClientBuilder.create()
                .setHostnameVerifier(SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER)
                .setSslcontext(sslContext).build();
    } else {/*from   w  w  w. ja v a 2s . co  m*/
        return HttpClientBuilder.create().build();
    }
}

From source file:kendzi.kendzi3d.service.viewer.service.OverpassService.java

/**
 * Run given query on overpass server./*from  w w  w  .j  a  v  a 2  s. c o  m*/
 * 
 * @param query
 *            query
 * @param encoding
 *            query encoding
 * @return response body
 */
public String findQuery(String query, String encoding) {

    HttpClient client = HttpClientBuilder.create().build();

    try {

        HttpPost post = new HttpPost(overpassUrl);

        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
        nameValuePairs.add(new BasicNameValuePair("data", query));

        post.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8"));

        HttpResponse response = client.execute(post);

        if (response == null) {
            throw new RuntimeException();
        }

        int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode != HttpStatus.SC_OK) {
            throw new IllegalStateException("overpass service returned error status: " + statusCode);
        }
        return EntityUtils.toString(response.getEntity(), "UTF-8");

    } catch (IOException e) {
        throw new IllegalStateException("error findQuery", e);
    }
}

From source file:com.esri.geoportal.harvester.waf.WafBroker.java

@Override
public void initialize(InitContext context) throws DataProcessorException {
    definition.override(context.getParams());
    td = context.getTask().getTaskDefinition();
    CloseableHttpClient client = HttpClientBuilder.create().useSystemProperties().build();
    if (context.getTask().getTaskDefinition().isIgnoreRobotsTxt()) {
        httpClient = client;/*from  w w w .  java  2 s  . c o m*/
    } else {
        Bots bots = BotsUtils.readBots(definition.getBotsConfig(), client, definition.getHostUrl());
        httpClient = new BotsHttpClient(client, bots);
    }
}

From source file:org.blocks4j.reconf.infra.http.layer.SimpleHttpClient.java

private static CloseableHttpClient newHttpClient(long timeout, TimeUnit timeUnit, int retries)
        throws GeneralSecurityException {
    return HttpClientBuilder.create().setRetryHandler(new RetryHandler(retries))
            .setDefaultRequestConfig(createBasicHttpParams(timeout, timeUnit)).build();
}

From source file:msgclient.ServerConnection.java

public JSONObject makeGetToServer(String path) {
    CloseableHttpResponse response;/*w w w . java  2s .c o  m*/
    JSONObject jsonObject = null;

    // Send a GET request to the server
    try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) {
        // Create a URI            
        URI uri = new URIBuilder().setScheme(PROTOCOL_TYPE).setHost(mServerName + ":" + mPort).setPath(path)
                .build();
        HttpGet httpget = new HttpGet(uri);
        httpget.addHeader("accept", "application/json");
        //System.out.println(httpget.getURI());

        response = httpClient.execute(httpget);
        if (response.getStatusLine().getStatusCode() == 200) {
            String jsonData = IOUtils.toString(response.getEntity().getContent());
            JSONParser parser = new JSONParser();
            Object obj = parser.parse(jsonData);
            jsonObject = (JSONObject) obj;
        } else {
            System.out.println(
                    "Received status code " + response.getStatusLine().getStatusCode() + " from server");
        }

        response.close();
        httpClient.close();
    } catch (Exception e) {
        System.out.println(e);
        return null;
    }

    return jsonObject;
}

From source file:com.questdb.test.tools.HttpTestUtils.java

private static HttpClientBuilder createHttpClient_AcceptsUntrustedCerts() throws Exception {
    HttpClientBuilder b = HttpClientBuilder.create();

    // setup a Trust Strategy that allows all certificates.
    ////w w w .  j  av a 2  s  . c o  m
    SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
        public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
            return true;
        }
    }).build();

    b.setSSLContext(sslContext);

    // here's the special part:
    //      -- need to create an SSL Socket Factory, to use our weakened "trust strategy";
    //      -- and create a Registry, to register it.
    //
    SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext,
            new HostnameVerifier() {
                @Override
                public boolean verify(String s, SSLSession sslSession) {
                    return true;
                }
            });
    Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
            .register("http", PlainConnectionSocketFactory.getSocketFactory())
            .register("https", sslSocketFactory).build();

    // now, we create connection-manager using our Registry.
    //      -- allows multi-threaded use
    b.setConnectionManager(new PoolingHttpClientConnectionManager(socketFactoryRegistry));

    return b;
}

From source file:com.arduino2fa.xbee.ReceivePacket.java

private ReceivePacket() throws Exception {
    XBee xbee = new XBee();

    int count = 0;
    int errors = 0;

    // Transmit stuff
    final int timeout = 5000;

    int ackErrors = 0;
    int ccaErrors = 0;
    int purgeErrors = 0;
    long now;//  www .  j  a  va  2 s.com

    // HTTP stuff
    CloseableHttpClient httpClient = HttpClientBuilder.create().build();
    HttpHost httpHost = new HttpHost("ec2-54-186-213-97.us-west-2.compute.amazonaws.com", 3000, "http");

    CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(new AuthScope(httpHost.getHostName(), httpHost.getPort()),
            new UsernamePasswordCredentials("admin", "admin") // TODO get from command line
    );

    // Create AuthCache instance
    AuthCache authCache = new BasicAuthCache();
    BasicScheme basicScheme = new BasicScheme();
    authCache.put(httpHost, basicScheme);

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

    HttpGet httpGet = new HttpGet("/token-requests/1");

    CloseableHttpResponse httpResponse;

    BufferedReader br;
    StringBuffer result;
    String line;

    try {
        // Connect to the XBee
        xbee.open(XbeeConfig.PORT, XbeeConfig.BAUD_RATE);

        now = System.currentTimeMillis();

        // Loop indefinitely; sleeps for a few seconds at the end of every iteration
        while (true) {

            // Check if there are queued tx requests on the server
            httpResponse = httpClient.execute(httpHost, httpGet, httpClientContext);
            br = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent()));

            result = new StringBuffer();

            while ((line = br.readLine()) != null) {
                result.append(line);
            }

            // Check if the result is a JSON object
            if (result.charAt(0) != '{') {
                log.error("Result " + result.toString() + " is not a JSON object");
                continue;
            }

            JSONObject object = (JSONObject) JSONValue.parse(result.toString());

            if (object != null) {
                Long time = (Long) object.get("time");

                // Check if the request is a new one (created after last check)
                if (time > last) {
                    String token = (String) object.get("token");
                    byte[] tokenHex = SimpleCrypto.toByte(token);

                    int[] payload = new int[] { tokenHex[0], tokenHex[1], tokenHex[2] };

                    XBeeAddress16 destination = new XBeeAddress16(0xFF, 0xFF);
                    TxRequest16 tx = new TxRequest16(destination, payload);

                    try {
                        log.info("sending tx request with payload: " + token);
                        XBeeResponse response = xbee.sendSynchronous(tx, timeout);

                        if (response.getApiId() != ApiId.TX_STATUS_RESPONSE) {
                            log.debug("expected tx status but received " + response);
                        } else {
                            log.debug("got tx status");

                            if (((TxStatusResponse) response).getFrameId() != tx.getFrameId()) {
                                throw new RuntimeException("frame id does not match");
                            }

                            if (((TxStatusResponse) response).getStatus() != TxStatusResponse.Status.SUCCESS) {
                                errors++;

                                if (((TxStatusResponse) response).isAckError()) {
                                    ackErrors++;
                                } else if (((TxStatusResponse) response).isCcaError()) {
                                    ccaErrors++;
                                } else if (((TxStatusResponse) response).isPurged()) {
                                    purgeErrors++;
                                }

                                log.debug("Tx status failure with status: "
                                        + ((TxStatusResponse) response).getStatus());
                            } else {
                                // success
                                log.debug("Success.  count is " + count + ", errors is " + errors + ", in "
                                        + (System.currentTimeMillis() - now) + ", ack errors " + ackErrors
                                        + ", ccaErrors " + ccaErrors + ", purge errors " + purgeErrors);
                            }

                            count++;

                        }
                    } catch (XBeeTimeoutException e) {
                        e.printStackTrace();
                    }
                }
            }

            last = System.currentTimeMillis();
            httpGet.releaseConnection();

            // Delay
            Thread.sleep(2000);
        }
    } finally {
        xbee.close();
    }
}

From source file:OandaProviderDriver.java

public ArrayList<SM230Candle> getRecentCandles(String instrument, String granularity, int count)
        throws ClientProtocolException, IOException {
    String normalized_instrument = instrument;

    // e.g., EUR/USD (ISO format) => EUR_USD (endpoint format)
    if (instrument.contains("/")) {
        normalized_instrument = instrument.replace("/", "_");
    }//from   w  w  w . ja  va 2  s.com

    HttpClient client = HttpClientBuilder.create().build();
    HttpGet request = new HttpGet("https://api-fxtrade.oanda.com/v3/instruments/" + normalized_instrument
            + "/candles?count=" + String.valueOf(count) + "&price=M&granularity=" + granularity);

    System.out.println("Api KEY: " + apiKey);

    request.addHeader("Content-Type", "application/json");
    request.addHeader("Authorization", "Bearer " + apiKey);
    HttpResponse response = client.execute(request);
    BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
    String line = "", l = "";

    while ((l = rd.readLine()) != null) {
        line += l;
    }

    System.out.println("Line: " + line);

    JSONObject root = new JSONObject(line);
    JSONArray candles_json = root.getJSONArray("candles");
    JSONObject candle_json, mid;

    ArrayList<SM230Candle> candles = new ArrayList<>();

    for (int i = 0; i < candles_json.length(); i++) {
        candle_json = candles_json.getJSONObject(i);
        mid = candle_json.getJSONObject("mid");

        SM230Candle candle = new SM230Candle(instrument,
                LocalDateTime.parse(candle_json.get("time").toString(),
                        DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSSSSSSSz")),
                granularity, Double.valueOf(mid.get("o").toString()), Double.valueOf(mid.get("h").toString()),
                Double.valueOf(mid.get("l").toString()), Double.valueOf(mid.get("c").toString()));

        candles.add(candle);
    }

    return candles;
}

From source file:org.elasticsearch.wildfly.WildflyIT.java

public void testTransportClient() throws URISyntaxException, IOException {
    try (CloseableHttpClient client = HttpClientBuilder.create().build()) {
        final String str = String.format(Locale.ROOT,
                "http://localhost:38080/wildfly-%s%s/transport/employees/1", Version.CURRENT,
                Build.CURRENT.isSnapshot() ? "-SNAPSHOT" : "");
        final HttpPut put = new HttpPut(new URI(str));
        final String body;
        try (XContentBuilder builder = jsonBuilder()) {
            builder.startObject();//from   w w  w .j  a  v  a  2  s  .  com
            {
                builder.field("first_name", "John");
                builder.field("last_name", "Smith");
                builder.field("age", 25);
                builder.field("about", "I love to go rock climbing");
                builder.startArray("interests");
                {
                    builder.value("sports");
                    builder.value("music");
                }
                builder.endArray();
            }
            builder.endObject();
            body = builder.string();
        }
        put.setEntity(new StringEntity(body, ContentType.APPLICATION_JSON));
        try (CloseableHttpResponse response = client.execute(put)) {
            assertThat(response.getStatusLine().getStatusCode(), equalTo(201));
        }

        final HttpGet get = new HttpGet(new URI(str));
        try (CloseableHttpResponse response = client.execute(get);
                XContentParser parser = JsonXContent.jsonXContent.createParser(
                        new NamedXContentRegistry(ClusterModule.getNamedXWriteables()),
                        response.getEntity().getContent())) {
            final Map<String, Object> map = parser.map();
            assertThat(map.get("first_name"), equalTo("John"));
            assertThat(map.get("last_name"), equalTo("Smith"));
            assertThat(map.get("age"), equalTo(25));
            assertThat(map.get("about"), equalTo("I love to go rock climbing"));
            final Object interests = map.get("interests");
            assertThat(interests, instanceOf(List.class));
            @SuppressWarnings("unchecked")
            final List<String> interestsAsList = (List<String>) interests;
            assertThat(interestsAsList, containsInAnyOrder("sports", "music"));
        }
    }
}

From source file:org.ow2.proactive.procci.service.RequestUtils.java

/**
 * Send a service to pca service with a header containing the session id and sending content
 *
 * @param content is which is send to the cloud automation service
 * @return the information about gathered from cloud automation service
 *///from  w  w w  .  j  a  va2s. co m
public JSONObject postRequest(JSONObject content, String url) {

    final String PCA_SERVICE_SESSIONID = "sessionid";
    try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) {
        HttpPost postRequest = new HttpPost(url);
        postRequest.addHeader(PCA_SERVICE_SESSIONID, getSessionId());
        StringEntity input = new StringEntity(content.toJSONString());
        input.setContentType("application/json");
        postRequest.setEntity(input);

        HttpResponse response = httpClient.execute(postRequest);

        String serverOutput = readHttpResponse(response, url, "POST " + content.toJSONString());
        return parseJSON(serverOutput);
    } catch (IOException ex) {
        logger.error(" IO exception in CloudAutomationInstanceClient::postRequest ", ex);
        throw new ServerException();
    }
}