Example usage for org.apache.http.impl.client HttpClients createDefault

List of usage examples for org.apache.http.impl.client HttpClients createDefault

Introduction

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

Prototype

public static CloseableHttpClient createDefault() 

Source Link

Document

Creates CloseableHttpClient instance with default configuration.

Usage

From source file:org.keycloak.quickstart.appjee.ServiceClient.java

public static String callService(HttpServletRequest req, KeycloakSecurityContext session, String action)
        throws Failure {
    HttpClient client = null;// w w  w.  ja v a  2  s  . c o  m
    try {
        client = HttpClients.createDefault();
        HttpGet get = new HttpGet(getServiceUrl(req, session) + "/" + action);
        if (session != null) {
            get.addHeader("Authorization", "Bearer " + session.getTokenString());
        }

        HttpResponse response = client.execute(get);

        StatusLine status = response.getStatusLine();
        if (status.getStatusCode() != 200) {
            throw new Failure(status.getStatusCode(), status.getReasonPhrase());
        }

        HttpEntity entity = response.getEntity();
        InputStream is = entity.getContent();
        try {
            MessageBean message = (MessageBean) JsonSerialization.readValue(is, MessageBean.class);
            return message.getMessage();
        } finally {
            is.close();
        }
    } catch (Failure f) {
        throw f;
    } catch (Exception e) {
        throw new RuntimeException(e);
    } finally {
        if (client != null)
            client.getConnectionManager().shutdown();
    }
}

From source file:org.cleverbus.core.common.directcall.DirectCallHttpImpl.java

@Override
public String makeCall(String callId) throws IOException {
    Assert.hasText(callId, "callId must not be empty");

    CloseableHttpClient httpClient = HttpClients.createDefault();

    try {/*from w  w  w . j  av  a2s  .  c  o m*/
        HttpGet httpGet = new HttpGet(localhostUri + RouteConstants.HTTP_URI_PREFIX
                + DirectCallWsRoute.SERVLET_URL + "?" + DirectCallWsRoute.CALL_ID_HEADER + "=" + callId);

        // Create a custom response handler
        ResponseHandler<String> responseHandler = new ResponseHandler<String>() {

            public String handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
                int status = response.getStatusLine().getStatusCode();
                if (status >= 200 && status < 300) {
                    // successful response
                    HttpEntity entity = response.getEntity();
                    return entity != null ? EntityUtils.toString(entity) : null;
                } else {
                    throw new IOException(EntityUtils.toString(response.getEntity()));
                }
            }
        };

        return httpClient.execute(httpGet, responseHandler);
    } finally {
        httpClient.close();
    }
}

From source file:org.nuxeo.elasticsearch.http.readonly.HttpClient.java

public static String get(String url, String payload) throws IOException {
    if (payload == null) {
        return get(url);
    }//from   w  w w  . j ava  2 s. c o m
    CloseableHttpClient client = HttpClients.createDefault();
    HttpGetWithEntity e = new HttpGetWithEntity(url);
    StringEntity myEntity = new StringEntity(payload,
            ContentType.create(MediaType.APPLICATION_FORM_URLENCODED, UTF8_CHARSET));
    e.setEntity(myEntity);
    try (CloseableHttpResponse response = client.execute(e)) {
        HttpEntity entity = response.getEntity();
        return entity != null ? EntityUtils.toString(entity) : null;
    }
}

From source file:br.cefetrj.sagitarii.teapot.comm.WebClient.java

public void doPost(String action, String parameter, String content) throws Exception {
    HttpClient httpclient = HttpClients.createDefault();
    HttpPost httppost = new HttpPost(gf.getHostURL() + "/" + action);

    // Request parameters and other properties.
    List<NameValuePair> params = new ArrayList<NameValuePair>(2);
    params.add(new BasicNameValuePair(parameter, content));
    //params.add(new BasicNameValuePair("param-2", "Hello!"));
    httppost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));

    httpclient.execute(httppost);//w  ww  .j  a va 2 s .c o m

}

From source file:com.jubination.io.chatbot.backend.service.core.LMSUpdater.java

public boolean createLead(User user) throws IOException {

    String responseText = null;/*from  ww w.jav a 2 s  .  co  m*/
    Document doc = null;
    CloseableHttpResponse response = null;
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder;
    InputSource is;
    try {
        //requesting exotel to initiate call
        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost("http://188.166.253.79/save_enquiry");
        List<NameValuePair> formparams = new ArrayList<>();

        formparams.add(new BasicNameValuePair("form_data[0][email_id]", user.getEmail()));
        formparams.add(new BasicNameValuePair("form_data[0][full_name]", user.getName()));
        formparams.add(new BasicNameValuePair("form_data[0][contact_no]", user.getPhone()));
        formparams.add(new BasicNameValuePair("form_data[0][city]", user.getCountry()));
        formparams.add(new BasicNameValuePair("form_data[0][ip]", "na"));
        if (user.getFbId() != null) {
            formparams.add(new BasicNameValuePair("form_data[0][campaign_id]", "162"));
            formparams.add(new BasicNameValuePair("form_data[0][source]", "fb-chatbot"));
        } else {
            formparams.add(new BasicNameValuePair("form_data[0][campaign_id]", "161"));
            formparams.add(new BasicNameValuePair("form_data[0][source]", "web-chatbot"));
        }
        formparams.add(new BasicNameValuePair("form_data[0][step_2]", "no"));
        formparams.add(new BasicNameValuePair("form_data[0][step_2_created_at]",
                new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())));
        LocalDateTime backdate = LocalDateTime.of(2013, Month.JANUARY, 1, 0, 0);
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        formparams.add(new BasicNameValuePair("form_data[0][step_2_inform_at]", backdate.format(formatter)));
        formparams.add(new BasicNameValuePair("form_data[0][chat_id]", user.getSesId()));
        for (Entry<String, Boolean> trigger : user.getTriggers().entrySet()) {
            formparams.add(new BasicNameValuePair("form_data[0][chat_" + trigger.getKey() + "]",
                    trigger.getValue().toString()));
        }

        UrlEncodedFormEntity uEntity = new UrlEncodedFormEntity(formparams, Consts.UTF_8);
        httpPost.setEntity(uEntity);
        response = httpclient.execute(httpPost);
        HttpEntity entity = response.getEntity();

        responseText = EntityUtils.toString(entity, "UTF-8");
    } catch (IOException | ParseException | DOMException e) {
        e.printStackTrace();
    } finally {
        if (response != null) {
            response.close();
        }
    }
    System.out.println(responseText);
    return responseText != null;
}

From source file:uk.trainwatch.util.config.impl.HttpConfiguration.java

private synchronized void loadConfiguration() {
    if (configuration == null) {
        // Don't write uri as is as we may expose security details
        LOG.log(Level.INFO,/*from  w  w  w .j  a v  a 2  s .  com*/
                () -> "Retrieving config " + uri.getScheme() + "://" + uri.getHost() + uri.getPath());

        try (CloseableHttpClient client = HttpClients.createDefault()) {
            int retry = 0;
            do {
                try {
                    if (retry > 0) {
                        LOG.log(Level.INFO, "Sleeping {0}ms attempt {1}/{2}",
                                new Object[] { RETRY_DELAY, retry, MAX_RETRY });
                        Thread.sleep(RETRY_DELAY);
                    }
                    HttpGet get = new HttpGet(uri);
                    get.setHeader("User-Agent", "Area51 Configuration/1.0");

                    try (CloseableHttpResponse response = client.execute(get)) {
                        switch (response.getStatusLine().getStatusCode()) {
                        case 200:
                        case 304:
                            try (InputStream is = response.getEntity().getContent()) {
                                try (JsonReader r = Json.createReader(new InputStreamReader(is))) {
                                    configuration = new MapConfiguration(
                                            MapBuilder.fromJsonObject(r.readObject()).build());
                                    return;
                                }
                            }

                        default:
                            LOG.log(Level.WARNING, () -> "Error " + uri.getScheme() + "://" + uri.getHost()
                                    + uri.getPath() + " " + response.getStatusLine().getStatusCode());
                        }
                    }
                } catch (ConnectException ex) {
                    if (retry < MAX_RETRY) {
                        LOG.log(Level.WARNING, () -> "Failed " + ex.getMessage());
                    } else {
                        throw ex;
                    }
                } catch (InterruptedException ex) {
                    LOG.log(Level.SEVERE, null, ex);
                }

                retry++;
            } while (retry < MAX_RETRY);
        } catch (IOException ex) {
            throw new UncheckedIOException(ex);
        }

        configuration = EmptyConfiguration.INSTANCE;
    }
}

From source file:uk.codingbadgers.bootstrap.download.EtagDownload.java

public void download() {
    CloseableHttpClient client = HttpClients.createDefault();
    HttpGet assetRequest = new HttpGet(remote);
    assetRequest.setHeader(new BasicHeader("Accept", BootstrapConstants.ASSET_MIME_TYPE));

    if (local.exists()) {
        assetRequest/*from   w  ww .j  av  a2s  .co m*/
                .setHeader(new BasicHeader("If-None-Match", "\"" + ChecksumGenerator.createMD5(local) + "\""));
    }

    try {
        HttpResponse response = client.execute(assetRequest);
        StatusLine status = response.getStatusLine();

        if (status.getStatusCode() == HttpStatus.SC_NOT_MODIFIED) {
            // No need to download, its already latest
            System.out.println("File " + local.getName() + " is up to date with remote, no need to download");
        } else if (status.getStatusCode() == HttpStatus.SC_MOVED_TEMPORARILY
                || status.getStatusCode() == HttpStatus.SC_OK) {
            // Update local version
            System.err.println("Downloading " + local.getName());

            HttpEntity entity = response.getEntity();

            ReadableByteChannel rbc = Channels.newChannel(entity.getContent());
            FileOutputStream fos = new FileOutputStream(local);
            fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);

            EntityUtils.consume(entity);

            String hash = "\"" + ChecksumGenerator.createMD5(local) + "\"";
            if (!hash.equalsIgnoreCase(response.getFirstHeader("Etag").getValue())) {
                throw new BootstrapException(
                        "Error downloading file (" + local.getName() + ")\n[expected hash: "
                                + response.getFirstHeader("Etag").getValue() + " but got " + hash + "]");
            }

            System.out.println("Downloaded " + local.getName());

        } else {
            throw new BootstrapException("Error getting update from github. Error: " + status.getStatusCode()
                    + status.getReasonPhrase());
        }
    } catch (IOException ex) {
        throw new BootstrapException(ex);
    } finally {
        close(client);
    }
}

From source file:ch.sbb.releasetrain.utils.http.HttpUtilImpl.java

/**
 * set user and password for basic authentication
 */// w  w w.  j a v  a  2  s  . c  o  m
@Override
public String getPageAsString(String url) {
    try {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpGet httpget = new HttpGet(url);
        httpget.setHeader("Cache-Control", "no-store");
        httpget.setHeader("Cache-Control", "no-cache");
        HttpClientContext context = initAuthIfNeeded(url);

        HttpResponse response = httpclient.execute(httpget, context);
        HttpEntity entity = response.getEntity();
        return EntityUtils.toString(entity);
    } catch (IOException e) {
        log.info(e.getMessage());
    }
    return "n/a";
}

From source file:org.fcrepo.camel.integration.FusekiContainerWrapper.java

@Override
@PostConstruct/*from  w ww  .j a v  a  2s  .co m*/
public void start() throws Exception {

    client = HttpClients.createDefault();

    final HttpGet method = new HttpGet(serverAddress);
    try {
        client.execute(method);

    } catch (final IOException e) {
        logger.debug("starting Fuseki");
        new Thread(new FusekiRunner()).start();
    }

    super.start();
}

From source file:eu.seaclouds.platform.dashboard.http.HttpGetRequestBuilder.java

@Override
public String build() throws IOException, URISyntaxException {
    URIBuilder uriBuilder = new URIBuilder();
    uriBuilder.setScheme(scheme);//  w w w  .ja  v  a2 s. co m
    if (host != null && path != null) {
        uriBuilder.setHost(host);
        uriBuilder.setPath(path);
        if (!params.isEmpty()) {
            uriBuilder.setParameters(params);
        }
    }
    requestBase = new HttpGet(uriBuilder.build());

    for (NameValuePair header : super.headers) {
        requestBase.addHeader(header.getName(), header.getValue());
    }

    try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
        return httpClient.execute(requestBase, responseHandler, context);
    }
}