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:com.cland.accessstats.util.QuickStart.java

public static void main(String[] args) throws Exception {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    try {/*from   w w  w .  j  a  v a2  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();
    }
}

From source file:org.apache.http.examples.client.ClientWithResponseHandler.java

public final static void main(String[] args) throws Exception {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    //    DefaultHttpParams.getDefaultParams().setParameter("http.protocol.cookie-policy", CookiePolicy.BROWSER_COMPATIBILITY);
    //    httpclient.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BEST_MATCH);
    try {//  w  w w  .j  av  a 2s  .  co  m
        //      HttpGet httpget = new HttpGet("http://localhost/");
        HttpGet httpget = new HttpGet(
                "http://api.map.baidu.com/geocoder/v2/?address=&output=json&ak=E4805d16520de693a3fe707cdc962045&callback=showLocation");
        //      httpget.setHeader("Accept", "180.97.33.90:80");
        httpget.setHeader("Accept",
                "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
        httpget.setHeader("Accept-Encoding", "gzip, deflate, sdch");
        httpget.setHeader("Accept-Language", "zh-CN,zh;q=0.8");
        httpget.setHeader("Cache-Control", "no-cache");
        httpget.setHeader("Connection", "keep-alive");
        httpget.setHeader("Referer",
                "http://developer.baidu.com/map/index.php?title=webapi/guide/changeposition");
        httpget.setHeader("User-Agent",
                "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.93 Safari/537.36");

        System.out.println("Executing request httpget.getRequestLine() " + httpget.getRequestLine());

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

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

        };
        String responseBody = httpclient.execute(httpget, responseHandler);
        System.out.println("----------------------------------------");
        System.out.println(responseBody);

        //showLocation&&showLocation({"status":0,"result":{"location":{"lng":112.25009284837,"lat":32.229168591538},"precise":0,"confidence":14,"level":"\u533a\u53bf"}})
        System.out.println("----------------------------------------");
        ObjectMapper mapper = new ObjectMapper();
        //      mapper.readValue(responseBody, AddressCoord.class);
        JsonNode root = mapper.readTree(
                responseBody.substring("showLocation&&showLocation(".length(), responseBody.length() - 1));
        //      String name = root.get("name").asText();
        //      int age = root.get("age").asInt();
        String status = root.get("status").asText();
        String lng = root.with("result").with("location").get("lng").asText();
        String lat = root.with("result").with("location").get("lat").asText();
        String level = root.with("result").get("level").asText();
        System.out.println(String.format("'%1$s': [%2$s, %3$s], status: %4$s", level, lng, lat, status));

    } finally {
        httpclient.close();
    }
}

From source file:testing01.QuickStart.java

public static void main(String[] args) throws Exception {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    String outputFile = "test.html";
    String baseWebSite = "http://www.ettoday.net/news/20130802/250478.htm";
    try {/*from   w w w  .  j  a  v a 2 s.  c o m*/
        //HttpGet httpGet = new HttpGet(baseWebSite + "cat/politic/r");
        HttpGet httpGet = new HttpGet(baseWebSite);
        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
            // and ensure it is fully consumed
            String responseString = EntityUtils.toString(entity1, "UTF-8");
            // System.out.println(responseString);
            Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outputFile), "UTF8"));
            out.write(responseString);
            out.close();
            EntityUtils.consume(entity1);
            System.out.println(baseWebSite + " output to " + outputFile + " successful");
        } catch (Exception e) {
            System.out.println(e.getMessage());
        } finally {
            response1.close();
        }
        /*
         * 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();
    }
}

From source file:org.apache.http.examples.client.ClientWithResponseHandlerForUms.java

public final static void main(String[] args) throws Exception {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    //    DefaultHttpParams.getDefaultParams().setParameter("http.protocol.cookie-policy", CookiePolicy.BROWSER_COMPATIBILITY);
    //    httpclient.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BEST_MATCH);
    try {/*  w w w  . java2  s. c  o  m*/
        //      String url = "http://mxyinghang.com/pay/ums/umsLogin.htm";
        String url = "http://cs.com:8080/web/ums/verify";
        HttpGet httpget = new HttpGet(url);
        httpget.setHeader("Accept",
                "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
        httpget.setHeader("Accept-Encoding", "gzip, deflate, sdch");
        httpget.setHeader("Accept-Language", "zh-CN,zh;q=0.8");
        httpget.setHeader("Cache-Control", "no-cache");
        httpget.setHeader("Connection", "keep-alive");
        httpget.setHeader("Referer", "http://mxyinghang.com/richboss/");
        httpget.setHeader("User-Agent",
                "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.93 Safari/537.36");

        System.out.println("Executing request httpget.getRequestLine() " + httpget.getRequestLine());

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

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

        };
        String responseBody = httpclient.execute(httpget, responseHandler);
        System.out.println("----------------------------------------");
        System.out.println(responseBody);

        System.out.println("----------------------------------------");
        //      ObjectMapper mapper = new ObjectMapper();
        //      mapper.readValue(responseBody, AddressCoord.class);
        //      JsonNode root = mapper.readTree(responseBody.substring("showLocation&&showLocation(".length(), responseBody.length()-1));

    } finally {
        httpclient.close();
    }
}

From source file:com.jivesoftware.os.amza.service.AmzaGetStress.java

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

    args = new String[] { "soa-integ-data11.phx1.jivehosted.com", "1185", "1", "10000" };

    final String hostName = args[0];
    final int port = Integer.parseInt(args[1]);
    final int firstDocId = Integer.parseInt(args[2]);
    final int count = Integer.parseInt(args[3]);
    final int batchSize = 100;

    String partitionName = "lorem";

    for (int i = 0; i < 1024; i++) {
        final String rname = partitionName + i;
        final org.apache.http.client.HttpClient httpClient = HttpClients.createDefault();

        Thread t = new Thread() {
            @Override//w w  w . j  a  v a2s  .co m
            public void run() {
                try {
                    get(httpClient, hostName, port, rname, 0, count, batchSize);
                } catch (Exception x) {
                    x.printStackTrace();
                }
            }
        };
        t.start();
    }
}

From source file:org.duracloud.syncui.SyncUIDriver.java

public static void main(String[] args) throws Exception {
    String url = "http://localhost:" + SyncUIConfig.getPort() + SyncUIConfig.getContextPath();
    CloseableHttpClient client = HttpClients.createDefault();

    if (isAppRunning(url, client)) {
        log.info("Sync Application already running, launching browser...");
        launchBrowser(url);/*ww  w  .ja  va 2  s  .c  om*/
    } else {
        log.info("Sync Application not yet running, launching server...");
        launchServer(url, client);
    }
}

From source file:ATTHackPause.Main.java

public static void main(String[] args) throws Exception {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    try {/*  w  w  w .ja v  a2  s  .  c o m*/
        HttpGet httpGet = new HttpGet(
                "https://api-m2x.att.com/v2/devices/ecbcc13b43417c6d9e1dc7618bbb1e6c/streams/");
        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
            // and ensure it is fully consumed
            EntityUtils.consume(entity1);
        } finally {
            response1.close();
        }

        HttpPost httpPost = new HttpPost(
                "https://api-m2x.att.com/v2/devices/ecbcc13b43417c6d9e1dc7618bbb1e6c/streams/Distance/values");
        // List <NameValuePair> nvps = new ArrayList <NameValuePair>();
        // nvps.add(new BasicNameValuePair("value", "15"));
        // nvps.add(new BasicNameValuePair("timestamp", "2016-04-09T19:37:42+00:00"));
        // httpPost.setEntity(new UrlEncodedFormEntity(nvps));

        String jsonString = "{\"values\":[{\"value\": \"99\",\"timestamp\": \"2016-04-09T20:43:49+00:00\"}]}";
        //System.out.println("\n\njsonString: " + jsonString);
        //            JSONArray jsonArray = new JSONArray(jsonString);
        //            System.out.println("\n\njsonArray: " + jsonArray);
        StringEntity se = new StringEntity(jsonString);
        httpPost.setEntity(se);

        httpPost.setHeader("Content-type", "application/json");
        httpPost.setHeader("X-M2X-KEY", "20bfa4a4f5ed88f94d772e8389e9a6d0");
        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();
    }
}

From source file:ClientWithResponseHandlerPost.java

public final static void main(String[] args) throws Exception {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    try {//from w  w  w . j  ava2 s  . co m
        List<NameValuePair> formparams = new ArrayList<NameValuePair>();
        formparams.add(new BasicNameValuePair("id", "KYacxNZ6QQc"));
        formparams.add(new BasicNameValuePair("calid", "adamm"));
        formparams.add(new BasicNameValuePair("content-out", "text/xml"));
        UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, Consts.UTF_8);

        //entity.setChunked(true);
        HttpPost httppost = new HttpPost("http://localhost:8080/export.wcap");
        httppost.setEntity(entity);

        System.out.println("executing request " + httppost.getURI());
        System.out.println("executing request " + httppost.getConfig());

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

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

        };
        String responseBody = httpclient.execute(httppost, responseHandler);
        System.out.println("----------------------------------------");
        System.out.println(responseBody);
        System.out.println("----------------------------------------");

    } 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);/* www.j  a va2s.  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());
            }

            consume(resEntity);

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

From source file:com.client.SoapClientApache.java

public static void main(String[] args) throws Exception {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    try {//w  w  w .  j ava  2 s . c o  m
        HttpGet httpGet = new HttpGet("http://google.com/");
        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 either fully consume the response content  or abort request
        // execution by calling CloseableHttpResponse#close().

        try {
            System.out.println("Response for http get");
            System.out.println(response1.getStatusLine());
            HttpEntity entity1 = response1.getEntity();
            // do something useful with the response body
            // and ensure it is fully consumed
            EntityUtils.consume(entity1);
        } finally {
            response1.close();
        }

        File file = new File("temConvertRq.xml");
        File fileOutXml = new File("temConvertRs.xml");
        fileOutXml.createNewFile();

        System.out.println("Before file entity");
        FileEntity entity = new FileEntity(file, ContentType.create("text/xml", "UTF-8"));

        System.out.println("Before http post");
        HttpPost httpPost = new HttpPost("http://www.w3schools.com/webservices/tempconvert.asmx");

        httpPost.setEntity(entity);
        System.out.println("Entity set");
        //Add headers
        httpPost.addHeader("SOAPAction", "http://www.w3schools.com/webservices/CelsiusToFahrenheit");
        httpPost.addHeader("Host", "www.w3schools.com");
        httpPost.addHeader("Content-Type", "text/xml; charset=utf-8");
        //httpPost.addHeader("Content-Length", "length");

        System.out.println("after headers added");
        CloseableHttpResponse response2 = httpclient.execute(httpPost);

        try {
            System.out.println("before getting the response status");
            System.out.println("Response Status= " + response2.getStatusLine());
            HttpEntity entity2 = response2.getEntity();
            String outXml = EntityUtils.toString(entity2);
            System.out.println("XMl Response!!!!!!!!! = " + outXml);

            //                entity2.writeTo(System.out);

            //System.out.println("R
            // do something useful with the response body
            // and ensure it is fully consumed
            EntityUtils.consume(entity2);

            FileUtils.writeStringToFile(fileOutXml, outXml, "UTF-8");

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