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.kookoo.outbound.OutboundTest.java

public static void main(String a[]) {
    try {//from   w ww .j  av  a2  s  .c  o  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:ui.pack.MyFrame.java

public static void main(String... args) throws IOException {
    //MyFrame mf= new MyFrame();
    HttpClient client = HttpClientBuilder.create().build();
    String url = "http://localhost:8080/students/all";
    HttpGet get = new HttpGet(url);
    HttpResponse response = client.execute(get);
    BufferedReader bufferedReader = new BufferedReader(
            new InputStreamReader(response.getEntity().getContent()));
    StringBuilder builder = new StringBuilder();
    while (true) {
        String line = bufferedReader.readLine();
        if (line == null) {
            break;
        } else {//from   ww w  . j  a  v  a  2s.c om
            builder.append(line);
        }
    }
    bufferedReader.close();
    String result = builder.toString();
    System.out.println(result);
    JSONArray arr = new JSONArray(result);
    System.out.println(arr.length());

    //client.
}

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

public static void main(String[] args) {
    // TODO code application logic here
    String url = "https://api.adorable.io/avatars/eyes1";
    try {/*from   w w  w.j  a va2 s. c o m*/
        HttpClient hc = HttpClientBuilder.create().build();
        HttpGet getMethod = new HttpGet(url);
        getMethod.addHeader("accept", "application/png");
        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("img.png"));
        int read = 0;
        byte[] bytes = new byte[2048];
        while ((read = is.read(bytes)) != -1) {
            os.write(bytes, 0, read);
        }
        is.close();
        os.close();
    } catch (IOException ex) {
        Logger.getLogger(SamplesUseHttpclient.class.getName()).log(Level.SEVERE, null, ex);
    }
}

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

public static void main(String[] args) {
    // TODO code application logic here
    String url = "https://api.adorable.io/avatars/eyes5";
    try {/*  w w  w  . ja v  a2  s  .c  o  m*/
        HttpClient hc = HttpClientBuilder.create().build();
        HttpGet getMethod = new HttpGet(url);
        getMethod.addHeader("accept", "application/png");
        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();

        Image image = ImageIO.read(is);
        JFrame frame = new JFrame();
        JLabel label = new JLabel(new ImageIcon(image));
        frame.getContentPane().add(label, BorderLayout.CENTER);
        frame.pack();
        frame.setVisible(true);

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

From source file:com.endava.webfundamentals.Main.java

public static void main(String[] args) throws JsonParseException, JsonMappingException, IOException {
    HttpClient httpClient = HttpClientBuilder.create().build();
    HttpGet httpRequest = new HttpGet("http://petstore.swagger.wordnik.com/api/api-docs");
    HttpResponse httpResponse = httpClient.execute(httpRequest);

    ObjectMapper objectMapper = new ObjectMapper();
    PetStore petStore = objectMapper.readValue(httpResponse.getEntity().getContent(), PetStore.class);

    PrintWriter out = new PrintWriter("PetStore.html");
    out.println("<html>");
    out.println("<header>");
    out.println(petStore.getInfo().getTitle());
    out.println("</header>");
    out.println("<body>");
    out.println("Api Version " + petStore.getApiVersion());
    out.println("Swagger Version " + petStore.getSwaggerVersion());
    out.println("<p>");
    out.println(petStore.getInfo().getDescription());
    out.println("</p>");
    out.println("<p>");
    out.println(petStore.getInfo().getContact());
    out.println("</p>");
    out.println(petStore.getInfo().getLicense());
    out.println(petStore.getInfo().getLicenseUrl());
    out.println("<p>");
    out.println(petStore.getInfo().getTermsOfServiceUrl());
    out.println("</p>");
    out.println("</body>");
    out.println("</html>");

    out.close();//ww  w  .  jav a2 s.  c  o m
}

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

public static void main(String[] args) {
    // TODO code application logic here
    String url = "http://username:password@10.49.28.3:8081/jasperserver/rest_v2/reports/Reportes/vencimientos.pdf?feini=2016-09-30&fefin=2016-09-30";
    try {//from  ww w .ja  va  2  s  . c  om
        HttpClient hc = HttpClientBuilder.create().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.anteam.demo.httpclient.PostDemo.java

public static void main(String[] args) {
    StringEntity stringEntity = new StringEntity("this is the log2.",
            ContentType.create("text/plain", "UTF-8"));
    HttpPost post = new HttpPost("http://127.0.0.1:9000");
    post.setEntity(stringEntity);//w  w  w . j  av a 2s.  com
    HttpClient httpclient = new DefaultHttpClient();

    // Execute the request
    HttpResponse response = null;
    try {
        response = httpclient.execute(post);
    } catch (ClientProtocolException e1) {
        e1.printStackTrace();
    } catch (IOException e1) {
        e1.printStackTrace();
    }

    // Examine the response status
    System.out.println(response.getStatusLine());

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

    // If the response does not enclose an entity, there is no need
    // to worry about connection release
    if (entity != null) {
        InputStream instream = null;
        try {
            instream = entity.getContent();

            BufferedReader reader = new BufferedReader(new InputStreamReader(instream));
            // do something useful with the response
            System.out.println(reader.readLine());

        } catch (Exception ex) {
            post.abort();

        } finally {

            try {
                instream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
        httpclient.getConnectionManager().shutdown();
    }
}

From source file:com.anteam.demo.logback.PostDemo.java

public static void main(String[] args) {
    StringEntity stringEntity = new StringEntity("this is the log2.",
            ContentType.create("text/plain", "UTF-8"));
    HttpPost post = new HttpPost("http://10.16.0.207:9000");
    post.setEntity(stringEntity);//from  w w w  . java  2s .c  om
    HttpClient httpclient = new DefaultHttpClient();

    // Execute the request
    HttpResponse response = null;
    try {
        response = httpclient.execute(post);
    } catch (ClientProtocolException e1) {
        e1.printStackTrace();
    } catch (IOException e1) {
        e1.printStackTrace();
    }

    // Examine the response status
    System.out.println(response.getStatusLine());

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

    // If the response does not enclose an entity, there is no need
    // to worry about connection release
    if (entity != null) {
        InputStream instream = null;
        try {
            instream = entity.getContent();

            BufferedReader reader = new BufferedReader(new InputStreamReader(instream));
            // do something useful with the response
            System.out.println(reader.readLine());

        } catch (Exception ex) {
            post.abort();

        } finally {

            try {
                instream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
        httpclient.getConnectionManager().shutdown();
    }
}

From source file:com.mycompany.mavenpost.HttpTest.java

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

    System.out.println("this is a test program");
    HttpPost httppost = new HttpPost("https://app.monsum.com/api/1.0/api.php");

    // Request parameters and other properties.
    String auth = DEFAULT_USER + ":" + DEFAULT_PASS;
    byte[] encodedAuth = Base64.encodeBase64(auth.getBytes());
    String authHeader = "Basic " + new String(encodedAuth);
    //String authHeader = "Basic " +"YW5kcmVhcy5zZWZpY2hhQG1hcmtldHBsYWNlLWFuYWx5dGljcy5kZTo5MGRkYjg3NjExMWRiNjNmZDQ1YzUyMjdlNTNmZGIyYlhtMUJQQm03OHhDS1FUVm1OR1oxMHY5TVVyZkhWV3Vh";

    httppost.setHeader(HttpHeaders.AUTHORIZATION, authHeader);

    httppost.setHeader(HttpHeaders.CONTENT_TYPE, "Content-Type: application/json");

    Map<String, Object> params = new LinkedHashMap<>();
    params.put("SERVICE", "customer.get");

    JSONObject json = new JSONObject();
    json.put("SERVICE", "customer.get");

    //Map<String, Object> params2 = new LinkedHashMap<>();

    //params2.put("CUSTOMER_NUMBER","5");
    JSONObject array = new JSONObject();
    array.put("CUSTOMER_NUMBER", "2");

    json.put("FILTER", array);

    StringEntity param = new StringEntity(json.toString());
    httppost.setEntity(param);//from  w  w w  .j  a  v  a  2  s  .co m

    HttpClient client = HttpClientBuilder.create().build();
    HttpResponse response = client.execute(httppost);

    int statusCode = response.getStatusLine().getStatusCode();
    System.out.println("The status code is  " + statusCode);

    //Execute and get the response.
    HttpEntity entity = response.getEntity();

    Header[] headers = response.getAllHeaders();
    for (Header header : headers) {
        System.out.println("Key : " + header.getName() + " ,Value : " + header.getValue());
    }
    if (entity != null) {
        String retSrc = EntityUtils.toString(entity); //Discouraged better open a stream and read the data as per Apache manual                     
        // parsing JSON
        //JSONObject result = new JSONObject(retSrc);
        Gson gson = new GsonBuilder().setPrettyPrinting().create();
        JsonParser jp = new JsonParser();
        JsonElement je = jp.parse(retSrc);
        String prettyJsonString = gson.toJson(je);
        System.out.println(prettyJsonString);
    }
    //if (entity != null) {
    //    InputStream instream = entity.getContent();
    //    try {
    //  final BufferedReader reader = new BufferedReader(
    //                    new InputStreamReader(instream));
    //            String line = null;
    //            while ((line = reader.readLine()) != null) {
    //                System.out.println(line);
    //            }
    //            reader.close();
    //    } finally {
    //        instream.close();
    //    }
    //}
}

From source file:web.restful.ClientTest.java

public static void main(String[] args) throws ClientProtocolException, IOException {
    HttpClient client = new DefaultHttpClient();
    HttpPut put = new HttpPut("http://localhost:8080/ss16-lab-web/resources/outliers/session");
    put.setEntity(new StringEntity("upenkwbq"));// session ID
    client.execute(put);
    put.releaseConnection();// ww w. j ava  2  s . c  o m

    put = new HttpPut("http://localhost:8080/ss16-lab-web/resources/outliers/bucket");
    put.setEntity(new StringEntity("Level1/Level1_Bin_1.txt")); // bucket name
    client.execute(put);
    put.releaseConnection();

    put = new HttpPut("http://localhost:8080/ss16-lab-web/resources/outliers/method");
    put.setEntity(new StringEntity("chauvenet")); // method name
    client.execute(put);
    put.releaseConnection();

    HttpGet get = new HttpGet("http://localhost:8080/ss16-lab-web/resources/outliers");
    HttpResponse response = client.execute(get);
    HttpEntity en = response.getEntity();
    InputStreamReader i = new InputStreamReader(en.getContent());
    BufferedReader rd = new BufferedReader(i);
    String line = "";
    while ((line = rd.readLine()) != null) {
        System.out.println(line);
    }
}