Example usage for org.apache.http.client HttpClient execute

List of usage examples for org.apache.http.client HttpClient execute

Introduction

In this page you can find the example usage for org.apache.http.client HttpClient execute.

Prototype

HttpResponse execute(HttpUriRequest request) throws IOException, ClientProtocolException;

Source Link

Document

Executes HTTP request using the default context.

Usage

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

public static void main(String[] args) {
    String url = "http://www.banxico.org.mx/tipcamb/llenarTiposCambioAction.do?idioma=sp";
    try {//from  w  w w . j a v a  2  s .c  om
        HttpClient hc = HttpClientBuilder.create().build();
        HttpGet request = new HttpGet(url);
        request.setHeader("User-Agent", "Mozilla/5.0");
        request.setHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");

        HttpResponse res = hc.execute(request);
        if (res.getStatusLine().getStatusCode() != 200) {
            throw new RuntimeException("Failed : HTTP eror code: " + res.getStatusLine().getStatusCode());
        }

        BufferedReader rd = new BufferedReader(new InputStreamReader(res.getEntity().getContent()));
        StringBuffer result = new StringBuffer();
        String line = "";
        while ((line = rd.readLine()) != null) {
            result.append(line);
        }
        Document doc = Jsoup.parse(result.toString());
        Element tipoCambioFix = doc.getElementById("FIX_DATO");
        System.out.println(tipoCambioFix.text());

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

From source file:com.hilatest.httpclient.apacheexample.ClientConnectionRelease.java

public final static void main(String[] args) throws Exception {
    HttpClient httpclient = new DefaultHttpClient();

    HttpGet httpget = new HttpGet("http://www.apache.org/");

    // Execute HTTP request
    System.out.println("executing request " + httpget.getURI());
    HttpResponse response = httpclient.execute(httpget);

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

    // Get hold of the response entity
    HttpEntity entity = response.getEntity();

    // If the response does not enclose an entity, there is no need
    // to bother about connection release
    if (entity != null) {
        BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent()));
        try {//from   w  ww.ja  v  a  2 s. c  om

            // do something useful with the response
            System.out.println(reader.readLine());

        } catch (IOException ex) {

            // In case of an IOException the connection will be released
            // back to the connection manager automatically
            throw ex;

        } catch (RuntimeException ex) {

            // In case of an unexpected exception you may want to abort
            // the HTTP request in order to shut down the underlying 
            // connection and release it back to the connection manager.
            httpget.abort();
            throw ex;

        } finally {

            // Closing the input stream will trigger connection release
            reader.close();

        }
    }

    // When HttpClient instance is no longer needed, 
    // shut down the connection manager to ensure
    // immediate deallocation of all system resources
    httpclient.getConnectionManager().shutdown();
}

From source file:com.mtea.macrotea_httpclient_study.ClientConnectionRelease.java

public final static void main(String[] args) throws Exception {
    HttpClient httpclient = new DefaultHttpClient();
    try {// w w w.  j a  v a2  s .co m
        HttpGet httpget = new HttpGet("http://www.apache.org/");

        // Execute HTTP request
        System.out.println("executing request " + httpget.getURI());
        HttpResponse response = httpclient.execute(httpget);

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

        HttpEntity entity = response.getEntity();

        //?????
        if (entity != null) {
            InputStream instream = entity.getContent();
            try {
                instream.read();
            } catch (IOException ex) {
                //IOExceptionConnectionManager
                throw ex;
            } catch (RuntimeException ex) {
                //RuntimeExceptionhttpget.abort();
                httpget.abort();
                throw ex;
            } finally {
                // instream.close() ?ConnectionManager
                try {
                    instream.close();
                } catch (Exception ignore) {
                }
            }
        }

    } finally {
        //??httpclient???
        httpclient.getConnectionManager().shutdown();
    }
}

From source file:com.caucho.hessian.client.ClientConnectionRelease.java

public final static void main(String[] args) throws Exception {
    HttpClient httpclient = new DefaultHttpClient();
    try {/*from  w  w  w  .j  av  a 2s  . co m*/
        HttpGet httpget = new HttpGet("http://www.apache.org/");

        // Execute HTTP request
        System.out.println("executing request " + httpget.getURI());
        HttpResponse response = httpclient.execute(httpget);

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

        // Get hold of the response entity
        HttpEntity entity = response.getEntity();

        // If the response does not enclose an entity, there is no need
        // to bother about connection release
        if (entity != null) {
            InputStream instream = entity.getContent();
            try {
                instream.read();
                // do something useful with the response
            } catch (IOException ex) {
                // In case of an IOException the connection will be released
                // back to the connection manager automatically
                throw ex;
            } catch (RuntimeException ex) {
                // In case of an unexpected exception you may want to abort
                // the HTTP request in order to shut down the underlying
                // connection immediately.
                httpget.abort();
                throw ex;
            } finally {
                // Closing the input stream will trigger connection release
                try {
                    instream.close();
                } catch (Exception ignore) {
                }
            }
        }

    } finally {
        // When HttpClient instance is no longer needed,
        // shut down the connection manager to ensure
        // immediate deallocation of all system resources
        httpclient.getConnectionManager().shutdown();
    }
}

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;//  ww w .  ja  v a2s .c  om
    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:OpenDataExtractor.java

public static void main(String[] args) {

    System.out.println("\nSeleziona in che campo fare la ricerca: ");
    System.out.println("Elenco completo delle gare in formato (1)"); // cc16106a-1a65-4c34-af13-cc045d181452
    System.out.println("Composizione delle commissioni giudicatrici (2)"); // c90f1ffb-c315-4f59-b0e3-b0f2f8709127
    System.out.println("Registro delle imprese escluse dalle gare (3)"); // 2ea798cc-1f52-4fc8-a28e-f92a6f409cb8
    System.out.println("Registro delle imprese invitate alle gare (4)"); // a124b6af-ae31-428a-8ac5-bb341feb3c46
    System.out.println("Registro delle imprese che hanno partecipato alle gare (5)");// e58396cf-1145-4cb1-84a4-34311238a0c6
    System.out.println("Anagrafica completa dei contratti per l'acquisizione di beni e servizi (6)"); // aa6a8664-5ef5-43eb-a563-910e25161798
    System.out.println("Fornitori (7)"); // 253c8ac9-8335-4425-84c5-4a90be863c00
    System.out.println("Autorizzazioni subappalti per i lavori  (8)"); // 4f9ba542-5768-4b39-a92a-450c45eabd5d
    System.out.println("Aggiudicazioni delle gare per i lavori (9)"); // 34e298ad-3a99-4feb-9614-b9c4071b9d8e
    System.out.println("Dati cruscotto lavori per area (10)"); // 1ee3ea1b-58e3-48bf-8eeb-36ac313eeaf8
    System.out.println("Dati cruscotto lavori per lotto (11)"); // cbededce-269f-48d2-8c25-2359bf246f42
    int count = 0;
    int scelta;/* www.  j  a v  a  2  s .  c  o  m*/
    String id_ref = "";
    Scanner scanner;

    try {

        do {
            scanner = new Scanner(System.in);
            scelta = scanner.nextInt();
            switch (scelta) {

            case 1:
                id_ref = "cc16106a-1a65-4c34-af13-cc045d181452&q=";
                break;
            case 2:
                id_ref = "c90f1ffb-c315-4f59-b0e3-b0f2f8709127&q=";
                break;
            case 3:
                id_ref = "2ea798cc-1f52-4fc8-a28e-f92a6f409cb8&q=";
                break;
            case 4:
                id_ref = "a124b6af-ae31-428a-8ac5-bb341feb3c46&q=";
                break;
            case 5:
                id_ref = "e58396cf-1145-4cb1-84a4-34311238a0c6&q=";
                break;
            case 6:
                id_ref = "aa6a8664-5ef5-43eb-a563-910e25161798&q=";
                break;
            case 7:
                id_ref = "253c8ac9-8335-4425-84c5-4a90be863c00&q=";
                break;
            case 8:
                id_ref = "4f9ba542-5768-4b39-a92a-450c45eabd5d&q=";
                break;
            case 9:
                id_ref = "34e298ad-3a99-4feb-9614-b9c4071b9d8e&q=";
                break;
            case 10:
                id_ref = "1ee3ea1b-58e3-48bf-8eeb-36ac313eeaf8&q=";
                break;
            case 11:
                id_ref = "cbededce-269f-48d2-8c25-2359bf246f42&q=";
                break;
            default:
                System.out.println("Numero non selezionabile");
                System.out.println("Reinserisci");
                break;

            }
        } while (scelta <= 0 || scelta > 11);

        scanner = new Scanner(System.in);

        System.out.println("Inserisci un parametro di ricerca: ");
        String record = scanner.nextLine();
        String limit = "&limit=10000";
        System.out.println("id di riferimento: " + id_ref);
        System.out.println("___________________________");
        String requestString = "http://dati.openexpo2015.it/catalog/api/action/datastore_search?resource_id="
                + id_ref + record + limit;
        HttpClient client = HttpClientBuilder.create().build();
        HttpGet request = new HttpGet(requestString);
        HttpResponse response = client.execute(request);

        BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
        String result = "";
        String resline = "";
        while ((resline = rd.readLine()) != null) {
            result += resline;
        }
        if (result != null) {
            JSONObject jsonObject = new JSONObject(result);
            JSONObject resultJson = (JSONObject) jsonObject.get("result");
            JSONArray resultJsonFields = (JSONArray) resultJson.get("fields");
            ArrayList<TypeFields> type = new ArrayList<TypeFields>();
            TypeFields type1;
            JSONObject temp;

            while (count < resultJsonFields.length()) {

                temp = (JSONObject) resultJsonFields.get(count);
                type1 = new TypeFields(temp.getString("id"), temp.getString("type"));
                type.add(type1);
                count++;
            }

            JSONArray arr = (JSONArray) resultJson.get("records");
            count = 0;

            while (count < arr.length()) {
                System.out.println("Entry numero: " + count);
                temp = (JSONObject) arr.get(count);
                for (TypeFields temp2 : type) {
                    System.out.println(temp2.nameType + ": " + temp.get(temp2.nameType));
                }
                count++;
                System.out.println("--------------------------");

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

}

From source file:org.vuphone.vandyupon.test.EventMetaRequestTester.java

public static void main(String[] args) {
    HttpClient c = new DefaultHttpClient();
    HttpPost post = new HttpPost("http://localhost:8080/vandyupon/events/");
    post.addHeader("Content-Type", "application/x-www-form-urlencoded");

    String params = "type=eventmetarequest&id=2&resp=xml";
    post.setEntity(new ByteArrayEntity(params.toString().getBytes()));

    try {/*  w ww.  j a  va 2 s. c o m*/
        HttpResponse resp = c.execute(post);
        resp.getEntity().writeTo(System.out);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:com.astrientlabs.nyt.NYT.java

public static void main(String[] args) {
     try {// www  .  j av  a2s .  c o m
         int session = 112;
         MembersResponse r = NYT.instance.getMembers(session, NYT.Branch.Senate, null, null);

         Member[] members = r.getItems();

         if (members != null) {
             String imgUrl;
             File dir = new File("/Users/rashidmayes/tmp/nyt/", String.valueOf(session));
             dir.mkdirs();
             File outDir;
             File outFile;
             for (Member member : members) {
                 System.out.println(member);
                 imgUrl = NYT.instance.extractImageURL(session, member);
                 System.out.println(imgUrl);
                 if (imgUrl != null) {
                     try {
                         HttpClient httpclient = new DefaultHttpClient();

                         HttpGet get = new HttpGet(imgUrl);
                         HttpResponse response = httpclient.execute(get);
                         if (response.getStatusLine().getStatusCode() == 200) {
                             outDir = new File(dir, member.getId());
                             outDir.mkdirs();
                             outFile = new File(outDir,
                                     (member.getFirst_name() + "." + member.getLast_name() + ".jpg")
                                             .toLowerCase());

                             FileOutputStream fos = null;
                             try {
                                 fos = new FileOutputStream(outFile);
                                 response.getEntity().writeTo(fos);
                             } finally {
                                 if (fos != null) {
                                     fos.close();
                                 }
                             }
                         }
                     } catch (Exception e) {
                         e.printStackTrace();
                     }
                 }
             }
         }
     } catch (JsonParseException e) {
         e.printStackTrace();
     } catch (JsonMappingException e) {
         e.printStackTrace();
     } catch (IOException e) {
         e.printStackTrace();
     }

     System.exit(0);
 }

From source file:org.vuphone.vandyupon.test.EventPostTester.java

public static void main(String[] args) {
    HttpClient c = new DefaultHttpClient();
    HttpPost post = new HttpPost("http://localhost:8080/vandyupon/events/");
    post.addHeader("Content-Type", "application/x-www-form-urlencoded");

    String params = "type=eventratingrequest&id=1&comments=true&numcom=10";
    post.setEntity(new ByteArrayEntity(params.toString().getBytes()));

    try {/*from   www. j a  v  a 2 s  .com*/
        HttpResponse resp = c.execute(post);
        resp.getEntity().writeTo(System.out);
    } catch (IOException e) {
        e.printStackTrace();
    }

}

From source file:org.vuphone.vandyupon.test.EventRatingPostTest.java

public static void main(String[] args) {
    HttpClient c = new DefaultHttpClient();
    HttpPost post = new HttpPost("http://localhost:8080/vandyupon/events/");
    post.addHeader("Content-Type", "application/x-www-form-urlencoded");

    String params = "type=eventratingpost&event=1&user=chris&comment=awesome&value=1&resp=xml";
    post.setEntity(new ByteArrayEntity(params.toString().getBytes()));

    try {//from   w  ww  .  ja  v  a  2s .  c o m
        HttpResponse resp = c.execute(post);
        resp.getEntity().writeTo(System.out);
    } catch (IOException e) {
        e.printStackTrace();
    }

}