Example usage for org.apache.http.impl.client CloseableHttpClient execute

List of usage examples for org.apache.http.impl.client CloseableHttpClient execute

Introduction

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

Prototype

public CloseableHttpResponse execute(final HttpUriRequest request) throws IOException, ClientProtocolException 

Source Link

Usage

From source file:com.bhc.test.ClientFormLogin.java

public static void main(String[] args) throws Exception {
    BasicCookieStore cookieStore = new BasicCookieStore();
    CloseableHttpClient httpclient = HttpClients.custom().setDefaultCookieStore(cookieStore).build();
    URI uri = null;/*from ww  w  .  j  a  v a  2  s .co  m*/
    try {
        uri = new URIBuilder().setScheme("https").setHost("user.qunar.com").setPath("/captcha/api/image")
                .setParameter("k", "{en7mni(z").setParameter("p", "ucenter_login")
                .setParameter("c", "ef7d278eca6d25aa6aec7272d57f0a9a")
                .setParameter("t", String.valueOf(new Date().getTime())).build();
        HttpGet httpget = new HttpGet(uri);
        CloseableHttpResponse response1 = httpclient.execute(httpget);
        try {
            HttpEntity entity = response1.getEntity();

            System.out.println("Login form get: " + response1.getStatusLine());
            EntityUtils.consume(entity);

            System.out.println("Initial set of cookies:");
            List<Cookie> cookies = cookieStore.getCookies();
            if (cookies.isEmpty()) {
                System.out.println("None");
            } else {
                for (int i = 0; i < cookies.size(); i++) {
                    System.out.println("- " + cookies.get(i).toString());
                }
            }
        } finally {
            response1.close();
        }

        HttpUriRequest login = RequestBuilder.post().setUri(new URI("https://someportal/"))
                .addParameter("IDToken1", "username").addParameter("IDToken2", "password").build();
        CloseableHttpResponse response2 = httpclient.execute(login);
        try {
            HttpEntity entity = response2.getEntity();

            System.out.println("Login form get: " + response2.getStatusLine());
            EntityUtils.consume(entity);

            System.out.println("Post logon cookies:");
            List<Cookie> cookies = cookieStore.getCookies();
            if (cookies.isEmpty()) {
                System.out.println("None");
            } else {
                for (int i = 0; i < cookies.size(); i++) {
                    System.out.println("- " + cookies.get(i).toString());
                }
            }
        } finally {
            response2.close();
        }
    } finally {
        httpclient.close();
    }
}

From source file:com.gemini.httpclienttest.HttpClientTestMain.java

public static void main(String[] args) {
    //authenticate with the server
    URL url;/*from   w w w.  ja v  a  2  s  .  c om*/
    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:edu.harvard.hul.ois.fits.clients.FormFileUploaderClientApplication.java

/**
 * Run the program.//from w w w. j  a  va 2 s  . c o m
 *
 * @param args First argument is path to the file to analyze; second (optional) is path to server for overriding default value.
 */
public static void main(String[] args) {
    // takes file path from first program's argument
    if (args.length < 1) {
        logger.error("****** Path to input file must be first argument to program! *******");
        logger.error("===== Exiting Program =====");
        System.exit(1);
    }

    String filePath = args[0];
    File uploadFile = new File(filePath);
    if (!uploadFile.exists()) {
        logger.error("****** File does not exist at expected locations! *******");
        logger.error("===== Exiting Program =====");
        System.exit(1);
    }

    if (args.length > 1) {
        serverUrl = args[1];
    }

    logger.info("File to upload: " + filePath);

    CloseableHttpClient httpclient = HttpClients.createDefault();
    try {
        HttpPost httppost = new HttpPost(serverUrl + "false");
        FileBody bin = new FileBody(uploadFile);
        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        builder.addPart(FITS_FORM_FIELD_DATAFILE, bin);
        HttpEntity reqEntity = builder.build();
        httppost.setEntity(reqEntity);

        logger.info("executing request " + httppost.getRequestLine());
        CloseableHttpResponse response = httpclient.execute(httppost);
        try {
            logger.info("HTTP Response Status Line: " + response.getStatusLine());
            // Expecting a 200 Status Code
            if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
                String reason = response.getStatusLine().getReasonPhrase();
                logger.warn("Unexpected HTTP response status code:[" + response.getStatusLine().getStatusCode()
                        + "] -- Reason (if available): " + reason);
            } else {
                HttpEntity resEntity = response.getEntity();
                InputStream is = resEntity.getContent();
                BufferedReader in = new BufferedReader(new InputStreamReader(is));

                String output;
                StringBuilder sb = new StringBuilder();
                while ((output = in.readLine()) != null) {
                    sb.append(output);
                    sb.append(System.getProperty("line.separator"));
                }
                logger.info(sb.toString());
                in.close();
                EntityUtils.consume(resEntity);
            }
        } finally {
            response.close();
        }
    } catch (Exception e) {
        logger.error("Caught exception: " + e.getMessage(), e);
    } finally {
        try {
            httpclient.close();
        } catch (IOException e) {
            logger.warn("Exception closing HTTP client: " + e.getMessage(), e);
        }
        logger.info("DONE");
    }
}

From source file:de.zazaz.iot.bosch.indego.App.java

public static void main(String[] args) throws ClientProtocolException, IOException, InterruptedException {
    CloseableHttpClient httpClient = HttpClients.createDefault();

    HttpPost httpPost = new HttpPost(BASE_URL_PUSHWOOSH + "registerDevice");
    String jsonPost = ""//
            + "{" //
            + "  \"request\":{" //
            + "     \"application\":\"8FF60-0666B\"," //
            + "     \"push_token\":\"124692134091\"," //
            + "     \"hwid\":\"00-0C-29-E8-B1-8D\"," //
            + "     \"timezone\":3600," //
            + "     \"device_type\":3" //
            + "  }" //
            + "}";
    httpPost.setEntity(new StringEntity(jsonPost, ContentType.APPLICATION_JSON));
    CloseableHttpResponse response = httpClient.execute(httpPost);

    System.out.println(response.getStatusLine());
    Header[] headers = response.getAllHeaders();
    for (int i = 0; i < headers.length; i++) {
        System.out.println(headers[i].getName() + ": " + headers[i].getValue());
    }/* w w  w .j a v  a  2s.c o  m*/
    HttpEntity entity = response.getEntity();
    String contents = EntityUtils.toString(entity);
    System.out.println(contents);

    Thread.sleep(5000);

    HttpPost httpGet = new HttpPost(BASE_URL_PUSHWOOSH + "checkMessage");
    String jsonGet = ""//
            + "{" //
            + "  \"request\":{" //
            + "     \"application\":\"8FF60-0666B\"," //
            + "     \"hwid\":\"00-0C-29-E8-B1-8D\"" //
            + "  }" //
            + "}";
    httpGet.setEntity(new StringEntity(jsonGet, ContentType.APPLICATION_JSON));
    httpClient.execute(httpGet);

    response.close();
}

From source file:demo.example.ClientMultipartFormPost.java

public static void main(String[] args) throws Exception {
    if (args.length != 1) {
        System.out.println("File path not given");
        System.exit(1);/*w  w w. j  a v  a 2  s.c  om*/
    }
    CloseableHttpClient httpclient = HttpClients.createDefault();
    try {
        HttpPost httppost = new HttpPost(
                "http://localhost:8080" + "/servlets-examples/servlet/RequestInfoExample");

        FileBody bin = new FileBody(new File(args[0]));
        StringBody comment = new StringBody("A binary file of some kind", ContentType.TEXT_PLAIN);

        HttpEntity reqEntity = MultipartEntityBuilder.create().addPart("bin", bin).addPart("comment", comment)
                .build();

        httppost.setEntity(reqEntity);

        System.out.println("executing request " + httppost.getRequestLine());
        CloseableHttpResponse response = httpclient.execute(httppost);
        try {
            System.out.println("----------------------------------------");
            System.out.println(response.getStatusLine());
            HttpEntity resEntity = response.getEntity();
            if (resEntity != null) {
                System.out.println("Response content length: " + resEntity.getContentLength());
            }
            EntityUtils.consume(resEntity);
        } finally {
            response.close();
        }
    } finally {
        httpclient.close();
    }
}

From source file:uk.ac.aber.dcs.cs22120.group16.utilities.ClientMultipartFormPost.java

public static void main(String[] args) throws Exception {
    if (args.length != 1) {
        System.out.println("File path not given");
        System.exit(1);//w w  w  .  j  a v a  2s.co  m
    }
    CloseableHttpClient httpclient = HttpClients.createDefault();
    try {
        HttpPost httppost = new HttpPost(
                "http://localhost:8080" + "/servlets-examples/servlet/RequestInfoExample");

        FileBody bin = new FileBody(new File(args[0]));
        StringBody comment = new StringBody("A binary file of some kind", ContentType.TEXT_PLAIN);

        HttpEntity reqEntity = MultipartEntityBuilder.create().addPart("bin", bin).addPart("comment", comment)
                .build();

        httppost.setEntity(reqEntity);

        System.out.println("executing request " + httppost.getRequestLine());
        CloseableHttpResponse response = httpclient.execute(httppost);
        try {
            System.out.println("----------------------------------------");
            System.out.println(response.getStatusLine());
            HttpEntity resEntity = response.getEntity();
            if (resEntity != null) {
                System.out.println("Response content length: " + resEntity.getContentLength());
            }

            consume(resEntity);

        } finally {
            response.close();
        }
    } finally {
        httpclient.close();
    }
}

From source file:interoperabilite.webservice.client.ClientEvictExpiredConnections.java

public static void main(String[] args) throws Exception {
    PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
    cm.setMaxTotal(100);/*from  ww  w .ja  v  a  2 s .c  o  m*/
    CloseableHttpClient httpclient = HttpClients.custom().setConnectionManager(cm).evictExpiredConnections()
            .evictIdleConnections(5L, TimeUnit.SECONDS).build();
    try {
        // create an array of URIs to perform GETs on
        String[] urisToGet = { "http://hc.apache.org/", "http://hc.apache.org/httpcomponents-core-ga/",
                "http://hc.apache.org/httpcomponents-client-ga/", };

        for (int i = 0; i < urisToGet.length; i++) {
            String requestURI = urisToGet[i];
            HttpGet request = new HttpGet(requestURI);

            System.out.println("Executing request " + requestURI);

            CloseableHttpResponse response = httpclient.execute(request);
            try {
                System.out.println("----------------------------------------");
                System.out.println(response.getStatusLine());
                System.out.println(EntityUtils.toString(response.getEntity()));
            } finally {
                response.close();
            }
        }

        PoolStats stats1 = cm.getTotalStats();
        System.out.println("Connections kept alive: " + stats1.getAvailable());

        // Sleep 10 sec and let the connection evictor do its job
        Thread.sleep(10000);

        PoolStats stats2 = cm.getTotalStats();
        System.out.println("Connections kept alive: " + stats2.getAvailable());

    } finally {
        httpclient.close();
    }
}

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

public static void main(String[] args) throws Exception {
    PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
    cm.setMaxTotal(100);/*from  w  w  w.j a v  a 2  s.com*/
    CloseableHttpClient httpclient = HttpClients.custom().setConnectionManager(cm).build();
    try {
        // create an array of URIs to perform GETs on
        String[] urisToGet = { "http://hc.apache.org/", "http://hc.apache.org/httpcomponents-core-ga/",
                "http://hc.apache.org/httpcomponents-client-ga/", };

        IdleConnectionEvictor connEvictor = new IdleConnectionEvictor(cm);
        connEvictor.start();

        for (int i = 0; i < urisToGet.length; i++) {
            String requestURI = urisToGet[i];
            HttpGet request = new HttpGet(requestURI);

            System.out.println("Executing request " + requestURI);

            CloseableHttpResponse response = httpclient.execute(request);
            try {
                System.out.println("----------------------------------------");
                System.out.println(response.getStatusLine());
                EntityUtils.consume(response.getEntity());
            } finally {
                response.close();
            }
        }

        // Sleep 10 sec and let the connection evictor do its job
        Thread.sleep(20000);

        // Shut down the evictor thread
        connEvictor.shutdown();
        connEvictor.join();

    } finally {
        httpclient.close();
    }
}

From source file:org.ege.httpclient.ClientAuthentication.java

public static void main(String[] args) throws Exception {
    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(new AuthScope(null, -1), new UsernamePasswordCredentials("alice", "alice"));

    Lookup<AuthSchemeProvider> basicAuthSchemeRegistry = RegistryBuilder.<AuthSchemeProvider>create()
            .register(AuthSchemes.BASIC, new BasicSchemeFactory()).build();
    Lookup<AuthSchemeProvider> spnegoAuthSchemeRegistry = RegistryBuilder.<AuthSchemeProvider>create()
            .register(AuthSchemes.SPNEGO, new SPNegoSchemeFactory(true)).build();

    CloseableHttpClient httpclient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider)
            .setDefaultAuthSchemeRegistry(spnegoAuthSchemeRegistry).build();

    //Lookup<AuthSchemeProvider> authProviders = RegistryBuilder.<AuthSchemeProvider>create().register(AuthSchemes.BASIC, new BasicSchemeFactory()).build();
    //Lookup<AuthSchemeProvider> authRegistry = <...>

    //HttpClientContext context = HttpClientContext.create();
    //context.setCredentialsProvider(credsProvider);
    //context.setAuthSchemeRegistry(authRegistry);

    try {/*from w w w.j  a v a2 s .  co  m*/
        HttpGet httpget = new HttpGet("http://lcom501d/hooks/hdr.cgi");

        System.out.println("Executing request " + httpget.getRequestLine());
        CloseableHttpResponse response = httpclient.execute(httpget);
        try {
            System.out.println("----------------------------------------");
            System.out.println(response.getStatusLine());
            EntityUtils.consume(response.getEntity());
        } finally {
            response.close();
        }
    } finally {
        httpclient.close();
    }
}

From source file:com.cland.accessstats.util.QuickStart.java

public static void main(String[] args) throws Exception {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    try {/*from   w  ww. j a va 2  s.c  o  m*/
        String origins = "-33.869952,18.537687";
        String destinations = "-33.96979309231926,18.53386491408955|-33.90630759128996,18.40310809285091|-33.97761,18.46555";
        String avoid = GMatrix.AVOID_HIGHWAYS + "|" + GMatrix.AVOID_TOLLS;
        String units = GMatrix.UNITS_DEFAULT;
        String language = "";
        boolean sensor = true;
        String url = GMatrix.getUrl(origins, destinations, GMatrix.JSON, GMatrix.MOD_DRIVING, avoid, units,
                language, sensor);
        System.out.println("Connection to... " + url);
        //GET EXAMPLE
        HttpGet httpGet = new HttpGet(url);
        CloseableHttpResponse response1 = httpclient.execute(httpGet);
        // The underlying HTTP connection is still held by the response object
        // to allow the response content to be streamed directly from the network socket.
        // In order to ensure correct deallocation of system resources
        // the user MUST call CloseableHttpResponse#close() from a finally clause.
        // Please note that if response content is not fully consumed the underlying
        // connection cannot be safely re-used and will be shut down and discarded
        // by the connection manager.
        try {
            System.out.println(response1.getStatusLine());
            HttpEntity entity1 = response1.getEntity();
            // do something useful with the response body
            String result = EntityUtils.toString(entity1);
            // and ensure it is fully consumed
            EntityUtils.consume(entity1);

            //Process the result json data in the the into a collection DataEntry objects
            int num = 3; //we requested for 3 destinations
            List<DataEntry> dataentries = new ArrayList<DataEntry>();
            for (int i = 0; i < num; i++) {
                String distance = GMatrix.getDistanceText(result, 0, i);
                String duration = GMatrix.getDurationText(result, 0, i);
                DataEntry d = new DataEntry();
                d.setName("DESTINATION " + (i + 1));
                d.setDistance(distance);
                d.setTravelTime(duration);
                dataentries.add(d);

                //                   System.out.println(">>> DESTINATION " + i);
                //                   System.out.println(">>>Distance text: " + distance);
                //                  System.out.println(">>>Duration : " + duration);

            } //end for loop

            //Now we can return the collection as JSON at this ONLY has google data only
            //Lets see wat we have so far

            for (DataEntry e : dataentries) {
                System.out.println(">>> " + e.getName() + ": Distance=" + e.getDistance() + ", Duration="
                        + e.getTravelTime());
            }

        } finally {
            response1.close();
        }

        // POST EXAMPLE
        //            HttpPost httpPost = new HttpPost("http://targethost/login");
        //            List <NameValuePair> nvps = new ArrayList <NameValuePair>();
        //            nvps.add(new BasicNameValuePair("username", "vip"));
        //            nvps.add(new BasicNameValuePair("password", "secret"));
        //            httpPost.setEntity(new UrlEncodedFormEntity(nvps));
        //            CloseableHttpResponse response2 = httpclient.execute(httpPost);
        //
        //            try {
        //                System.out.println(response2.getStatusLine());
        //                HttpEntity entity2 = response2.getEntity();
        //                // do something useful with the response body
        //                // and ensure it is fully consumed
        //                EntityUtils.consume(entity2);
        //            } finally {
        //                response2.close();
        //            }
    } finally {
        httpclient.close();
    }
}