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:com.gemini.httpclienttest.HttpClientTestMain.java

public static void main(String[] args) {
    //authenticate with the server
    URL url;/*from w w  w .  j a v a  2  s . c o m*/
    try {
        url = new URL("http://198.11.209.34:5000/v2.0/tokens");
    } catch (MalformedURLException ex) {
        System.out.printf("Invalid Endpoint - not a valid URL {}", "http://198.11.209.34:5000/v2.0");
        return;
    }
    CloseableHttpClient httpclient = HttpClientBuilder.create().build();
    try {
        HttpPost httpPost = new HttpPost(url.toString());
        httpPost.setHeader("Content-Type", "application/json");
        StringEntity strEntity = new StringEntity(
                "{\"auth\":{\"tenantName\":\"Gemini-network-prj\",\"passwordCredentials\":{\"username\":\"sri\",\"password\":\"srikumar12\"}}}");
        httpPost.setEntity(strEntity);
        //System.out.println("Executing request " + httpget.getRequestLine());
        CloseableHttpResponse response = httpclient.execute(httpPost);
        try {
            //get the response status code 
            String respStatus = response.getStatusLine().getReasonPhrase();

            //get the response body
            int bytes = response.getEntity().getContent().available();
            InputStream body = response.getEntity().getContent();
            BufferedReader in = new BufferedReader(new InputStreamReader(body));
            String line;
            StringBuffer sbJSON = new StringBuffer();
            while ((line = in.readLine()) != null) {
                sbJSON.append(line);
            }
            String json = sbJSON.toString();
            EntityUtils.consume(response.getEntity());

            GsonBuilder gsonBuilder = new GsonBuilder();
            Object parsedJson = gsonBuilder.create().fromJson(json, Object.class);
            System.out.printf("Parsed json is of type %s\n\n", parsedJson.getClass().toString());
            if (parsedJson instanceof com.google.gson.internal.LinkedTreeMap) {
                com.google.gson.internal.LinkedTreeMap treeJson = (com.google.gson.internal.LinkedTreeMap) parsedJson;
                if (treeJson.containsKey("id")) {
                    String s = (String) treeJson.getOrDefault("id", "no key provided");
                    System.out.printf("\n\ntree contained id %s\n", s);
                } else {
                    System.out.printf("\n\ntree does not contain key id\n");
                }
            }
        } catch (IOException ex) {
            System.out.print(ex);
        } finally {
            response.close();
        }
    } catch (IOException ex) {
        System.out.print(ex);
    } finally {
        //lots of exceptions, just the connection and exit
        try {
            httpclient.close();
        } catch (IOException | NoSuchMethodError ex) {
            System.out.print(ex);
            return;
        }
    }
}

From source file:com.oeg.oops.Main.java

public static void main(String[] args) {
    System.out.println("Hello, World");

    for (int i = 0; i < args.length; i++) {
        System.out.println("arg: " + args[i]);
    }//from  w  w w.  j a  va  2 s  .  com
    //        if(args.length<2){
    //            System.out.println("expect 2 arguments: vocabulary-uri and output-directory");
    //        }
    //        else{
    //            String uri = args[0];
    //            String output_dir = args[1];
    if (true) {
        String uri = "https://raw.githubusercontent.com/ahmad88me/demo/master/alo.owl";
        String output_dir = "./output";

        System.out.println("uri: " + uri);
        System.out.println("output dir: " + output_dir);

        try {

            HttpClient client = HttpClientBuilder.create().build();
            HttpGet request = new HttpGet(uri);
            request.setHeader("Accept", "application/rdf+xml");
            HttpResponse response = client.execute(request);
            if (response.getStatusLine().getStatusCode() == 200) {
                String contentType = response.getFirstHeader("Content-Type").getValue();
                System.out.println("content type: " + contentType);
            }
        } catch (Exception e) {
            System.err.println("Error while doing http get: " + " in " + uri + " " + e.getMessage());
        }

        //Vocabulary v = new Vocabulary(uri);
        //            CreateOOPSEvalPage coep = new CreateOOPSEvalPage(v);
        //            coep.createPage(output_dir);
    }

}

From source file:CalcoloRitardiLotti.java

public static void main(String[] args) {
    String id_ref = "cbededce-269f-48d2-8c25-2359bf246f42";
    String requestString = "http://dati.openexpo2015.it/catalog/api/action/datastore_search?resource_id="
            + id_ref;//  w  w w. j av a  2 s. com
    HttpClient client = HttpClientBuilder.create().build();
    HttpGet request = new HttpGet(requestString);
    try {

        HttpResponse response = client.execute(request);
        BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
        String result = "";
        String resline = "";
        Calendar c = Calendar.getInstance();
        Date current = Date.valueOf(
                c.get(Calendar.YEAR) + "-" + (c.get(Calendar.MONTH) + 1) + "-" + c.get(Calendar.DAY_OF_MONTH));
        while ((resline = rd.readLine()) != null)
            result += resline;

        //System.out.println(jsonObject.toString());
        if (result != null) {
            JSONObject jsonObject = new JSONObject(result);
            JSONObject resultJson = (JSONObject) jsonObject.get("result");
            JSONArray records = (JSONArray) resultJson.get("records");
            Date temp1, temp2;
            //System.out.printf(records.toString());
            long diffInizioFineLavori;
            long ritardo;
            long den = (24 * 60 * 60 * 1000);
            JSONObject temp;

            DefaultCategoryDataset cdata = new DefaultCategoryDataset();
            String partialQuery;
            DefaultPieDataset data = new DefaultPieDataset();

            String totalQuery = "";
            int countSospesi = 0;
            int countConclusi = 0;
            int countVerifica = 0;
            int countInCorso = 0;
            int countCollaudo = 0;
            String stato;
            for (int i = 0; i < records.length(); i++) {
                temp = (JSONObject) records.get(i);
                temp1 = Date.valueOf((temp.getString("Data Consegna Lavori")).substring(0, 10));
                temp2 = Date.valueOf((temp.getString("Data Fine lavori")).substring(0, 10));
                diffInizioFineLavori = (long) (temp2.getTime() - temp1.getTime()) / den;
                stato = temp.getString("STATO");
                if (stato.equals("Concluso"))
                    countConclusi++;
                else if (stato.equals("In corso"))
                    countInCorso++;
                else if (stato.contains("Verifiche"))
                    countVerifica++;
                else if (stato.contains("Collaudo sospeso") || stato.contains("sospeso"))
                    countSospesi++;
                else
                    countCollaudo++;

                if (!temp.getString("STATO").equals("Concluso") && temp2.getTime() < current.getTime())
                    ritardo = (long) (current.getTime() - temp2.getTime()) / den;
                else
                    ritardo = 0;

                cdata.setValue(ritardo, String.valueOf(i + 1), String.valueOf(i + 1));
                System.out.println(
                        "Opera: " + temp.getString("Oggetto del lotto") + " | id: " + temp.getInt("_id"));
                System.out.println("Data consegna lavoro: " + temp.getString("Data Consegna Lavori")
                        + " | Data fine lavoro: " + temp.getString("Data Fine lavori"));
                System.out.println("STATO: " + temp.getString("STATO"));
                System.out.println("Differenza in giorni: " + diffInizioFineLavori
                        + " | Numero giorni contrattuali: " + temp.getString("numero di giorni contrattuali"));
                System.out.println("Ritardo accumulato: " + ritardo);

                System.out.println("----------------------------------");

                partialQuery = "\nid: " + temp.getInt("_id") + "\nOpera:" + temp.getString("Oggetto del lotto")
                        + "\n" + "Data consegna lavoro: " + temp.getString("Data Consegna Lavori")
                        + "Data fine lavoro: " + temp.getString("Data Fine lavori") + "\n" + "STATO: "
                        + temp.getString("STATO") + "\n" + "Differenza in giorni: " + diffInizioFineLavori
                        + " - Numero giorni contrattuali: " + temp.getString("numero di giorni contrattuali")
                        + "\n" + "Ritardo accumulato: " + ritardo + "\n"
                        + "----------------------------------\n";
                totalQuery = totalQuery + partialQuery;

            }

            JFreeChart chart1 = ChartFactory.createBarChart3D("RITARDI AL " + current, "Id lotto",
                    "ritardo(in giorni)", cdata);
            ChartRenderingInfo info = null;
            ChartUtilities.saveChartAsPNG(
                    new File(System.getProperty("user.dir") + "/istogramma" + current + ".png"), chart1, 1500,
                    1500, info, true, 10);
            FileUtils.writeStringToFile(new File(current + "_1.txt"), totalQuery);

            data.setValue("Conclusi: " + countConclusi, countConclusi);
            data.setValue("Sospeso: " + countSospesi, countSospesi);
            data.setValue("In Corso: " + countInCorso, countInCorso);
            data.setValue("Verifica: " + countVerifica, countVerifica);
            data.setValue("Collaudo: " + countCollaudo, countCollaudo);
            JFreeChart chart2 = ChartFactory.createPieChart3D("Statistiche del " + current, data, true, true,
                    true);
            ChartUtilities.saveChartAsPNG(new File(System.getProperty("user.dir") + "/pie" + current + ".png"),
                    chart2, 800, 450);

        }

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

From source file:com.mycompany.horus.Teste.java

public static void main(String[] args) throws Exception {

    ServiceListener list = new ServiceListener();
    list.getHorusServicesList();//  w  w  w  .ja  v a  2 s.  c o  m

    String soapBody = "<soap:Envelope xmlns:soap=\"http://www.w3.org/2003/05/soap-envelope\" xmlns:est=\"http://servicos.saude.gov.br/horus/v1r0/EstoqueService\">\n"
            + " <soap:Header>\n"
            + " <wsse:Security xmlns:wsse=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wsswssecurity-secext-1.0.xsd\">\n"
            + " <wsse:UsernameToken wsu:Id=\"Id-0001334008436683-000000002c4a1908-1\" xmlns:wsu=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd\">\n"
            + " <wsse:Username>HORUS</wsse:Username>\n"
            + " <wsse:Password Type=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wssusername-token-profile-1.0#PasswordText\">SENHA</wsse:Password>\n"
            + " </wsse:UsernameToken>\n" + " </wsse:Security>\n" + " </soap:Header>\n"
            + " <soap:Body><est:requestConsultarPosicaoEstoquePorCNES>\n" + " <est:cnes>7604041</est:cnes>\n"
            + " </est:requestConsultarPosicaoEstoquePorCNES>\n" + " </soap:Body>\n" + "</soap:Envelope>\n";
    try {
        // Get target URL

        CloseableHttpClient httpclient = HttpClientBuilder.create().build();
        StringEntity strEntity = new StringEntity(soapBody, "UTF-8");
        strEntity.setContentType("text/xml");
        HttpPost post = new HttpPost("https://servicos.saude.gov.br/horus/v1r0/EstoqueService");
        post.setEntity(strEntity);

        // Execute request
        HttpResponse response = httpclient.execute(post);
        HttpEntity respEntity = response.getEntity();
        String resp = EntityUtils.toString(respEntity);
        if (respEntity != null) {
            System.out.println("Response:");
            System.out.println(resp);
            //Changing response to Xml file
            stringToDom(resp);

        } else {
            System.out.println("No Response");
        }
    } catch (Exception e) {
        System.out.println("Other exception = " + e.toString());
    }
}

From source file:com.kookoo.outbound.OutboundTest.java

public static void main(String a[]) {
    try {// w  ww.j a v a  2  s . co m
        String server_ip = "http://XXXX:8080"; /*change to your web server*/
        String phone_no1 = "09985XXXXX";/*change number to your numbers*/
        String phone_no2 = "09985XXXXX";/*change number to your numbers*/
        String api_key = "KKXXXXX";/*kookoo api key*/
        String kookoo_number = "91xxxxx";/*kookoo assigned number*/

        Date d = new Date();
        String trackId = "" + d.getTime();
        String url = "http://kookoo.in/outbound/outbound.php";
        URIBuilder uribuilder = new URIBuilder(url);
        uribuilder.addParameter("api_key", api_key);
        uribuilder.addParameter("phone_no", phone_no1);
        uribuilder.addParameter("caller_id", kookoo_number);
        /*assigned kookoo number*/
        uribuilder.addParameter("url",
                server_ip + "/kookoocall/outboundcall?number2=" + phone_no2 + "&trackId=" + trackId);
        uribuilder.addParameter("callback_url",
                server_ip + "/kookoocall/outbound_callstatus?number2=" + phone_no2 + "&trackId=" + trackId);

        URI uri = uribuilder.build();
        System.out.println("Final Outboud API url " + uri);
        HttpGet request = new HttpGet(uri);
        HttpClient client = HttpClientBuilder.create().build();
        HttpResponse response = client.execute(request);

        String responseString = new BasicResponseHandler().handleResponse(response);
        System.out.println(responseString);

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

}

From source file:org.ado.biblio.desktop.BulkBookLoad.java

public static void main(String[] args) throws IOException {
    HttpClient client = HttpClientBuilder.create().build();
    HttpGet request = new HttpGet(
            "https://www.kimonolabs.com/api/43h8bb74?apikey=a506e75ca96092b0f73b0ff59c15abe6");
    HttpResponse response = client.execute(request);

    LOGGER.info("Response code [{}]", response.getStatusLine().getStatusCode());

    String responseContent = IOUtils.toString(response.getEntity().getContent());
    final KimonoIsbn kimonoIsbn = new Gson().fromJson(responseContent, KimonoIsbn.class);
    LOGGER.info(kimonoIsbn.toString());/*w w w.j  ava2 s  .c o m*/

    final List<StringMap> books = kimonoIsbn.getResults().get("books");
    for (StringMap book : books) {
        final String isbnUrl = (String) book.get("isbn");
        LOGGER.info(isbnUrl);
        send(isbnUrl);
    }
}

From source file:com.rest.samples.getReportFromJasperServerWithSeparateAuth.java

public static void main(String[] args) {
    // TODO code application logic here

    String host = "10.49.28.3";
    String port = "8081";
    String reportName = "vencimientos";
    String params = "feini=2016-09-30&fefin=2016-09-30";
    String url = "http://{host}:{port}/jasperserver/rest_v2/reports/Reportes/{reportName}.pdf?{params}";
    url = url.replace("{host}", host);
    url = url.replace("{port}", port);
    url = url.replace("{reportName}", reportName);
    url = url.replace("{params}", params);

    try {/*w  w w . j  a v  a  2s. c o  m*/
        CredentialsProvider cp = new BasicCredentialsProvider();
        cp.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("username", "password"));
        CloseableHttpClient hc = HttpClientBuilder.create().setDefaultCredentialsProvider(cp).build();

        HttpGet getMethod = new HttpGet(url);
        getMethod.addHeader("accept", "application/pdf");
        HttpResponse res = hc.execute(getMethod);
        if (res.getStatusLine().getStatusCode() != 200) {
            throw new RuntimeException("Failed : HTTP eror code: " + res.getStatusLine().getStatusCode());
        }

        InputStream is = res.getEntity().getContent();
        OutputStream os = new FileOutputStream(new File("vencimientos.pdf"));
        int read = 0;
        byte[] bytes = new byte[2048];

        while ((read = is.read(bytes)) != -1) {
            os.write(bytes, 0, read);
        }
        is.close();
        os.close();

        if (Desktop.isDesktopSupported()) {
            File pdfFile = new File("vencimientos.pdf");
            Desktop.getDesktop().open(pdfFile);
        }

    } catch (IOException ex) {
        Logger.getLogger(SamplesUseHttpclient.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:com.rest.samples.getReportFromJasperServerWithSeparateAuthFormatURL.java

public static void main(String[] args) {
    // TODO code application logic here
    Map<String, String> params = new HashMap<String, String>();
    params.put("host", "10.49.28.3");
    params.put("port", "8081");
    params.put("reportName", "vencimientos");
    params.put("parametros", "feini=2016-09-30&fefin=2016-09-30");
    StrSubstitutor sub = new StrSubstitutor(params, "{", "}");
    String urlTemplate = "http://{host}:{port}/jasperserver/rest_v2/reports/Reportes/{reportName}.pdf?{parametros}";
    String url = sub.replace(urlTemplate);

    try {/* w  w w . j a v a2s.c om*/
        CredentialsProvider cp = new BasicCredentialsProvider();
        cp.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("jasperadmin", "jasperadmin"));
        CloseableHttpClient hc = HttpClientBuilder.create().setDefaultCredentialsProvider(cp).build();

        HttpGet getMethod = new HttpGet(url);
        getMethod.addHeader("accept", "application/pdf");
        HttpResponse res = hc.execute(getMethod);
        if (res.getStatusLine().getStatusCode() != 200) {
            throw new RuntimeException("Failed : HTTP eror code: " + res.getStatusLine().getStatusCode());
        }

        InputStream is = res.getEntity().getContent();
        OutputStream os = new FileOutputStream(new File("vencimientos.pdf"));
        int read = 0;
        byte[] bytes = new byte[2048];

        while ((read = is.read(bytes)) != -1) {
            os.write(bytes, 0, read);
        }
        is.close();
        os.close();

        if (Desktop.isDesktopSupported()) {
            File pdfFile = new File("vencimientos.pdf");
            Desktop.getDesktop().open(pdfFile);
        }

    } catch (IOException ex) {
        Logger.getLogger(SamplesUseHttpclient.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:org.jboss.teiid.quickstart.PortfolioHTTPClient.java

public static void main(String[] args) throws URISyntaxException, UnsupportedEncodingException {

    String hostname = "localhost";
    int port = 8080;
    String username = "restUser";
    String password = "password1!";
    if (args.length == 4) {
        hostname = args[0];/*from  w w  w .  ja v a 2 s . c om*/
        port = Integer.parseInt(args[1]);
        username = args[2];
        password = args[3];
    }

    HttpClientBuilder builder = HttpClientBuilder.create();
    HttpHost targetHost = new HttpHost(hostname, port);
    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    AuthScope scope = new AuthScope(targetHost.getHostName(), targetHost.getPort());
    UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(username, password);
    credsProvider.setCredentials(scope, credentials);
    builder.setDefaultCredentialsProvider(credsProvider);
    HttpClient client = builder.build();

    execute(client, new HttpGet("http://localhost:8080/PortfolioRest_1/Rest/foo/1"));
    execute(client, new HttpGet("http://localhost:8080/PortfolioRest_1/Rest/getAllStocks"));
    execute(client, new HttpGet("http://localhost:8080/PortfolioRest_1/Rest/getAllStockById/1007"));
    execute(client, new HttpGet("http://localhost:8080/PortfolioRest_1/Rest/getAllStockBySymbol/IBM"));

}

From source file:com.lxf.spider.client.ClientWithRequestFuture.java

public static void main(String[] args) throws Exception {
    // the simplest way to create a HttpAsyncClientWithFuture
    HttpClient httpclient = HttpClientBuilder.create().setMaxConnPerRoute(5).setMaxConnTotal(5).build();
    ExecutorService execService = Executors.newFixedThreadPool(5);
    FutureRequestExecutionService requestExecService = new FutureRequestExecutionService(httpclient,
            execService);/*from   w  ww  .  j  a va 2 s  .  c o m*/
    try {
        // Because things are asynchronous, you must provide a ResponseHandler
        ResponseHandler<Boolean> handler = new ResponseHandler<Boolean>() {
            public Boolean handleResponse(HttpResponse response) throws ClientProtocolException, IOException {
                // simply return true if the status was OK
                return response.getStatusLine().getStatusCode() == 200;
            }
        };

        // Simple request ...
        HttpGet request1 = new HttpGet("http://google.com");
        HttpRequestFutureTask<Boolean> futureTask1 = requestExecService.execute(request1,
                HttpClientContext.create(), handler);
        Boolean wasItOk1 = futureTask1.get();
        System.out.println("It was ok? " + wasItOk1);

        // Cancel a request
        try {
            HttpGet request2 = new HttpGet("http://google.com");
            HttpRequestFutureTask<Boolean> futureTask2 = requestExecService.execute(request2,
                    HttpClientContext.create(), handler);
            futureTask2.cancel(true);
            Boolean wasItOk2 = futureTask2.get();
            System.out.println("It was cancelled so it should never print this: " + wasItOk2);
        } catch (CancellationException e) {
            System.out.println("We cancelled it, so this is expected");
        }

        // Request with a timeout
        HttpGet request3 = new HttpGet("http://google.com");
        HttpRequestFutureTask<Boolean> futureTask3 = requestExecService.execute(request3,
                HttpClientContext.create(), handler);
        Boolean wasItOk3 = futureTask3.get(10, TimeUnit.SECONDS);
        System.out.println("It was ok? " + wasItOk3);

        FutureCallback<Boolean> callback = new FutureCallback<Boolean>() {
            public void completed(Boolean result) {
                System.out.println("completed with " + result);
            }

            public void failed(Exception ex) {
                System.out.println("failed with " + ex.getMessage());
            }

            public void cancelled() {
                System.out.println("cancelled");
            }
        };

        // Simple request with a callback
        HttpGet request4 = new HttpGet("http://google.com");
        // using a null HttpContext here since it is optional
        // the callback will be called when the task completes, fails, or is cancelled
        HttpRequestFutureTask<Boolean> futureTask4 = requestExecService.execute(request4,
                HttpClientContext.create(), handler, callback);
        Boolean wasItOk4 = futureTask4.get(10, TimeUnit.SECONDS);
        System.out.println("It was ok? " + wasItOk4);
    } finally {
        requestExecService.close();
    }
}