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.lxf.spider.client.QuickStart.java

public static void main(String[] args) throws Exception {
    InputStream input = null;/*from  www  . java 2 s .com*/
    OutputStream output = null;
    //httpclient
    CloseableHttpClient httpclient = HttpClients.createDefault();
    try {
        //get
        HttpGet httpGet = new HttpGet("http://127.0.0.1:8080/pdqx.jc.web/cen/center.html");
        //
        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 {
            //???
            int statusCode = response1.getStatusLine().getStatusCode();
            //??200?
            if (statusCode == HttpStatus.SC_OK) {
                //                  input = httpGet.getRequestLine();
                System.out.println(response1.getStatusLine());
                //
                HttpEntity entity1 = response1.getEntity();
                // do something useful with the response body
                // and ensure it is fully consumed
                input = entity1.getContent();
                output = new FileOutputStream("d:/lxf.data");
                //?
                int tempByte = -1;
                while ((tempByte = input.read()) > 0) {
                    output.write(tempByte);
                }
                EntityUtils.consume(entity1);
                //?
                if (input != null) {
                    input.close();
                }
                if (output != null) {
                    output.close();
                }
            }

        } 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:com.lexmark.saperion.util.ClientMultipartFormPost.java

public static void main(String[] args) throws Exception {
    String userName = "amolugu";
    String password = "ecm";
    String authString = userName + ":" + password;
    byte[] authEncBytes = Base64.encodeBase64(authString.getBytes());
    String authStringEnc = new String(authEncBytes);
    CloseableHttpClient httpclient = HttpClients.createDefault();
    try {/* w  ww  . jav  a  2s  .c om*/
        HttpPost httpPost = new HttpPost("https://ecm-service.psft.co/ecms/documents");

        //http
        httpPost.addHeader("Authorization", "Basic " + authStringEnc);
        httpPost.addHeader("Accept", "application/json");
        httpPost.addHeader("saTenant", "india");
        httpPost.addHeader("saLicense", "1");
        httpPost.addHeader("Content-Type", "application/octet-stream");

        FileBody bin = new FileBody(new File("C:\\Users\\Aditya.Molugu\\workspace\\RestClient\\Binaries.txt"));
        StringBody comment = new StringBody("A binary file of some kind", ContentType.TEXT_PLAIN);

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

        //HttpBo
        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:com.networknt.light.server.handler.loader.PageLoader.java

public static void main(String[] args) {
    try {/*from w  w  w  .  j  a v a  2  s.  co  m*/
        String host = null;
        String userId = null;
        String password = null;
        if (args != null && args.length == 3) {
            host = args[0];
            userId = args[1];
            password = args[2];
            if (host.length() == 0 || userId.length() == 0 || password.length() == 0) {
                System.out.println("host, userId and password are required");
                System.exit(1);
            }
        } else {
            System.out.println("Usage: PageLoader host userId password");
            System.exit(1);
        }

        File folder = getFileFromResourceFolder(pageFolder);
        if (folder != null) {
            httpclient = HttpClients.createDefault();
            // login as owner here
            login(host, userId, password);
            getPageMap(host);

            File[] listOfFiles = folder.listFiles();
            for (int i = 0; i < listOfFiles.length; i++) {
                loadPageFile(host, listOfFiles[i]);
            }
            httpclient.close();
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
    }
}

From source file:com.rslakra.testcases.apache.TestApacheHttpClasses.java

/**
 * /*from w ww .  j  a  va2  s  . com*/
 * @param args
 * @throws Exception
 */
public static void main(String[] args) throws Exception {
    CloseableHttpClient httpClient = HttpClients.createDefault();
    final String urlString = "https://qawest.meetx.org/";

    CloseableHttpResponse httpResponse = null;

    try {
        HttpGet httpGet = new HttpGet(urlString);
        httpResponse = 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(httpResponse.getStatusLine());
            Header[] headers = httpGet.getAllHeaders();
            for (Header header : headers) {
                System.out.println(header.getName() + "=" + header.getValue());
            }

            HttpEntity httpEntity = httpResponse.getEntity();
            // do something useful with the response body
            // and ensure it is fully consumed
            EntityUtils.consume(httpEntity);
        } finally {
            if (httpResponse != null) {
                httpResponse.close();
            }
        }

        // HttpPost httpPost = new HttpPost(urlString);
        // 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:com.newproject.ApacheHttp.java

public static void main(String[] args) throws Exception {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    String jsonFilePath = "/Users/vikasmohandoss/Documents/Cloud/test.txt";
    String url = "http://www.sentiment140.com/api/bulkClassifyJson&appid=vm2446@columbia.edu";
    JSONParser jsonParser = new JSONParser();
    JSONObject jsonObject = new JSONObject();
    URL obj = new URL(url);
    HttpURLConnection con = (HttpURLConnection) obj.openConnection();
    try {/*w  w w. j  a v a2 s  .  c  o  m*/
        FileReader fileReader = new FileReader(jsonFilePath);
        jsonObject = (JSONObject) jsonParser.parse(fileReader);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (ParseException e) {
        e.printStackTrace();
    }
    System.out.println(jsonObject.toString());
    /*try {
    /*HttpGet httpGet = new HttpGet("http://httpbin.org/get");
    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("http://httpbin.org/post");
    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();
    }*/
    try {
        HttpPost request = new HttpPost("http://www.sentiment140.com/api/bulkClassifyJson");
        StringEntity params = new StringEntity(jsonObject.toString());
        request.addHeader("content-type", "application/json");
        request.setEntity(params);
        HttpResponse response = httpclient.execute(request);
        System.out.println(response.toString());
        String result = EntityUtils.toString(response.getEntity());
        System.out.println(result);
        try {
            File file = new File("/Users/vikasmohandoss/Documents/Cloud/sentiment.txt");
            // if file doesnt exists, then create it
            if (!file.exists()) {
                file.createNewFile();
            }
            FileWriter fw = new FileWriter(file.getAbsoluteFile());
            BufferedWriter bw = new BufferedWriter(fw);
            bw.write(result);
            bw.close();
            System.out.println("Done");
        } catch (IOException e) {
            e.printStackTrace();
        }
        // handle response here...
    } catch (Exception ex) {
        // handle exception here
    } finally {
        httpclient.close();
    }
}

From source file:com.networknt.light.server.handler.loader.FormLoader.java

public static void main(String[] args) {
    try {//  ww  w .jav  a 2 s. co  m
        String host = null;
        String userId = null;
        String password = null;
        if (args != null && args.length == 3) {
            host = args[0];
            userId = args[1];
            password = args[2];
            if (host.length() == 0 || userId.length() == 0 || password.length() == 0) {
                System.out.println("host, userId and password are required");
                System.exit(1);
            }
        } else {
            System.out.println("Usage: FormLoader host userId password");
            System.exit(1);
        }
        File folder = getFileFromResourceFolder(formFolder);
        if (folder != null) {
            httpclient = HttpClients.createDefault();
            // login as owner here
            login(host, userId, password);
            // get formMap for comparison
            getFormMap(host);

            File[] listOfFiles = folder.listFiles();
            for (int i = 0; i < listOfFiles.length; i++) {
                loadFormFile(host, listOfFiles[i]);
            }
            httpclient.close();
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
    }
}

From source file:com.linkedin.pinotdruidbenchmark.PinotResponseTime.java

public static void main(String[] args) throws Exception {
    if (args.length != 4 && args.length != 5) {
        System.err.println(//from  ww w .  j av  a2s.c  om
                "4 or 5 arguments required: QUERY_DIR, RESOURCE_URL, WARM_UP_ROUNDS, TEST_ROUNDS, RESULT_DIR (optional).");
        return;
    }

    File queryDir = new File(args[0]);
    String resourceUrl = args[1];
    int warmUpRounds = Integer.parseInt(args[2]);
    int testRounds = Integer.parseInt(args[3]);
    File resultDir;
    if (args.length == 4) {
        resultDir = null;
    } else {
        resultDir = new File(args[4]);
        if (!resultDir.exists()) {
            if (!resultDir.mkdirs()) {
                throw new RuntimeException("Failed to create result directory: " + resultDir);
            }
        }
    }

    File[] queryFiles = queryDir.listFiles();
    assert queryFiles != null;
    Arrays.sort(queryFiles);

    try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
        HttpPost httpPost = new HttpPost(resourceUrl);

        for (File queryFile : queryFiles) {
            String query = new BufferedReader(new FileReader(queryFile)).readLine();
            httpPost.setEntity(new StringEntity("{\"pql\":\"" + query + "\"}"));

            System.out.println(
                    "--------------------------------------------------------------------------------");
            System.out.println("Running query: " + query);
            System.out.println(
                    "--------------------------------------------------------------------------------");

            // Warm-up Rounds
            System.out.println("Run " + warmUpRounds + " times to warm up...");
            for (int i = 0; i < warmUpRounds; i++) {
                CloseableHttpResponse httpResponse = httpClient.execute(httpPost);
                httpResponse.close();
                System.out.print('*');
            }
            System.out.println();

            // Test Rounds
            System.out.println("Run " + testRounds + " times to get response time statistics...");
            long[] responseTimes = new long[testRounds];
            long totalResponseTime = 0L;
            for (int i = 0; i < testRounds; i++) {
                long startTime = System.currentTimeMillis();
                CloseableHttpResponse httpResponse = httpClient.execute(httpPost);
                httpResponse.close();
                long responseTime = System.currentTimeMillis() - startTime;
                responseTimes[i] = responseTime;
                totalResponseTime += responseTime;
                System.out.print(responseTime + "ms ");
            }
            System.out.println();

            // Store result.
            if (resultDir != null) {
                File resultFile = new File(resultDir, queryFile.getName() + ".result");
                CloseableHttpResponse httpResponse = httpClient.execute(httpPost);
                try (BufferedInputStream bufferedInputStream = new BufferedInputStream(
                        httpResponse.getEntity().getContent());
                        BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(resultFile))) {
                    int length;
                    while ((length = bufferedInputStream.read(BYTE_BUFFER)) > 0) {
                        bufferedWriter.write(new String(BYTE_BUFFER, 0, length));
                    }
                }
                httpResponse.close();
            }

            // Process response times.
            double averageResponseTime = (double) totalResponseTime / testRounds;
            double temp = 0;
            for (long responseTime : responseTimes) {
                temp += (responseTime - averageResponseTime) * (responseTime - averageResponseTime);
            }
            double standardDeviation = Math.sqrt(temp / testRounds);
            System.out.println("Average response time: " + averageResponseTime + "ms");
            System.out.println("Standard deviation: " + standardDeviation);
        }
    }
}

From source file:PinotResponseTime.java

public static void main(String[] args) throws Exception {
    try (CloseableHttpClient client = HttpClients.createDefault()) {
        HttpPost post = new HttpPost("http://localhost:8099/query");
        CloseableHttpResponse res;//w  w  w.  java 2  s  .c  o  m

        if (STORE_RESULT) {
            File dir = new File(RESULT_DIR);
            if (!dir.exists()) {
                dir.mkdirs();
            }
        }

        int length;

        // Make sure all segments online
        System.out.println("Test if number of records is " + RECORD_NUMBER);
        post.setEntity(new StringEntity("{\"pql\":\"select count(*) from tpch_lineitem\"}"));
        while (true) {
            System.out.print('*');
            res = client.execute(post);
            boolean valid;
            try (BufferedInputStream in = new BufferedInputStream(res.getEntity().getContent())) {
                length = in.read(BUFFER);
                valid = new String(BUFFER, 0, length, "UTF-8").contains("\"value\":\"" + RECORD_NUMBER + "\"");
            }
            res.close();
            if (valid) {
                break;
            } else {
                Thread.sleep(5000);
            }
        }
        System.out.println("Number of Records Test Passed");

        // Start Benchmark
        for (int i = 0; i < QUERIES.length; i++) {
            System.out.println(
                    "--------------------------------------------------------------------------------");
            System.out.println("Start running query: " + QUERIES[i]);
            post.setEntity(new StringEntity("{\"pql\":\"" + QUERIES[i] + "\"}"));

            // Warm-up Rounds
            System.out.println("Run " + WARMUP_ROUND + " times to warm up cache...");
            for (int j = 0; j < WARMUP_ROUND; j++) {
                res = client.execute(post);
                if (!isValid(res, null)) {
                    System.out.println("\nInvalid Response, Sleep 20 Seconds...");
                    Thread.sleep(20000);
                }
                res.close();
                System.out.print('*');
            }
            System.out.println();

            // Test Rounds
            int[] time = new int[TEST_ROUND];
            int totalTime = 0;
            int validIdx = 0;
            System.out.println("Run " + TEST_ROUND + " times to get average time...");
            while (validIdx < TEST_ROUND) {
                long startTime = System.currentTimeMillis();
                res = client.execute(post);
                long endTime = System.currentTimeMillis();
                boolean valid;
                if (STORE_RESULT && validIdx == 0) {
                    valid = isValid(res, RESULT_DIR + File.separator + i + ".json");
                } else {
                    valid = isValid(res, null);
                }
                if (!valid) {
                    System.out.println("\nInvalid Response, Sleep 20 Seconds...");
                    Thread.sleep(20000);
                    res.close();
                    continue;
                }
                res.close();
                time[validIdx] = (int) (endTime - startTime);
                totalTime += time[validIdx];
                System.out.print(time[validIdx] + "ms ");
                validIdx++;
            }
            System.out.println();

            // Process Results
            double avgTime = (double) totalTime / TEST_ROUND;
            double stdDev = 0;
            for (int temp : time) {
                stdDev += (temp - avgTime) * (temp - avgTime) / TEST_ROUND;
            }
            stdDev = Math.sqrt(stdDev);
            System.out.println("The average response time for the query is: " + avgTime + "ms");
            System.out.println("The standard deviation is: " + stdDev);
        }
    }
}

From source file:net.cloudkit.relaxation.HttpClientTest.java

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

    InetAddress[] addresss = InetAddress.getAllByName("google.com");
    for (InetAddress address : addresss) {

        System.out.println(address);

    }/*from   w ww .ja  v a  2 s.  c o m*/

    CloseableHttpClient httpclient = HttpClients.createDefault();

    String __VIEWSTATE = "";
    String __EVENTVALIDATION = "";

    HttpGet httpGet = new HttpGet("http://query.customs.gov.cn/MNFTQ/MRoadQuery.aspx?" + Math.random() * 1000);
    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,en;q=0.6");
    httpGet.setHeader("Cache-Control", "no-cache");
    // httpGet.setHeader("Connection", "keep-alive");
    httpGet.setHeader("Host", "query.customs.gov.cn");
    httpGet.setHeader("Pragma", "no-cache");
    httpGet.setHeader("Upgrade-Insecure-Requests", "1");
    httpGet.setHeader("User-Agent",
            "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36");

    HttpClientContext context = HttpClientContext.create();
    // CloseableHttpResponse response1 = httpclient.execute(httpGet, context);
    CloseableHttpResponse response1 = httpclient.execute(httpGet);
    // Header[] headers = response1.getHeaders(HttpHeaders.CONTENT_TYPE);
    // System.out.println("context cookies:" + context.getCookieStore().getCookies());
    // String setCookie = response1.getFirstHeader("Set-Cookie").getValue();
    // System.out.println("context cookies:" + setCookie);

    try {
        System.out.println(response1.getStatusLine());
        HttpEntity entity1 = response1.getEntity();
        // do something useful with the response body and ensure it is fully consumed

        String result = IOUtils.toString(entity1.getContent(), "GBK");
        // System.out.println(result);

        Matcher m1 = Pattern.compile(
                "<input type=\\\"hidden\\\" name=\\\"__VIEWSTATE\\\" id=\\\"__VIEWSTATE\\\" value=\\\"(.*)\\\" />")
                .matcher(result);
        __VIEWSTATE = m1.find() ? m1.group(1) : "";
        Matcher m2 = Pattern.compile(
                "<input type=\\\"hidden\\\" name=\\\"__EVENTVALIDATION\\\" id=\\\"__EVENTVALIDATION\\\" value=\\\"(.*)\\\" />")
                .matcher(result);
        __EVENTVALIDATION = m2.find() ? m2.group(1) : "";

        System.out.println(__VIEWSTATE);
        System.out.println(__EVENTVALIDATION);

        /*
        File storeFile = new File("D:\\customs\\customs"+ i +".jpg");
        FileOutputStream output = new FileOutputStream(storeFile);
        IOUtils.copy(input, output);
        output.close();
        */
        EntityUtils.consume(entity1);
    } finally {
        response1.close();
    }

    HttpPost httpPost = new HttpPost(
            "http://query.customs.gov.cn/MNFTQ/MRoadQuery.aspx?" + Math.random() * 1000);
    httpPost.setHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
    httpPost.setHeader("Accept-Encoding", "gzip, deflate");
    httpPost.setHeader("Accept-Language", "zh-CN,zh;q=0.8,en;q=0.6");
    httpPost.setHeader("Cache-Control", "no-cache");
    // httpPost.setHeader("Connection", "keep-alive");
    httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");
    httpPost.setHeader("Cookie", "ASP.NET_SessionId=t1td453hcuy4oqiplekkqe55");
    httpPost.setHeader("Host", "query.customs.gov.cn");
    httpPost.setHeader("Origin", "http://query.customs.gov.cn");
    httpPost.setHeader("Pragma", "no-cache");
    httpPost.setHeader("Referer", "http://query.customs.gov.cn/MNFTQ/MRoadQuery.aspx");
    httpPost.setHeader("Upgrade-Insecure-Requests", "1");
    httpPost.setHeader("User-Agent",
            "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36");

    List<NameValuePair> nvps = new ArrayList<NameValuePair>();
    nvps.add(new BasicNameValuePair("__VIEWSTATE", __VIEWSTATE));
    nvps.add(new BasicNameValuePair("__EVENTVALIDATION", __EVENTVALIDATION));
    nvps.add(new BasicNameValuePair("ScrollTop", ""));
    nvps.add(new BasicNameValuePair("__essVariable", ""));
    nvps.add(new BasicNameValuePair("MRoadQueryCtrl1$txtManifestID", "5100312462240"));
    nvps.add(new BasicNameValuePair("MRoadQueryCtrl1$txtBillNo", "7PH650021105"));
    nvps.add(new BasicNameValuePair("MRoadQueryCtrl1$txtCode", "a778"));
    nvps.add(new BasicNameValuePair("MRoadQueryCtrl1$btQuery", "   "));
    nvps.add(new BasicNameValuePair("select", ""));
    nvps.add(new BasicNameValuePair("select1", ""));
    nvps.add(new BasicNameValuePair("select2", ""));
    nvps.add(new BasicNameValuePair("select3", ""));
    nvps.add(new BasicNameValuePair("select4", ""));
    nvps.add(new BasicNameValuePair("select5", "??"));
    nvps.add(new BasicNameValuePair("select6", ""));
    nvps.add(new BasicNameValuePair("select7", ""));
    nvps.add(new BasicNameValuePair("select8", ""));

    httpPost.setEntity(new UrlEncodedFormEntity(nvps, "GBK"));

    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
        // System.out.println(entity2.getContent());
        System.out.println(IOUtils.toString(response2.getEntity().getContent(), "GBK"));

        EntityUtils.consume(entity2);
    } finally {
        response2.close();
    }

}

From source file:com.linkedin.pinotdruidbenchmark.DruidResponseTime.java

public static void main(String[] args) throws Exception {
    if (args.length != 4 && args.length != 5) {
        System.err.println(/*from   w  w  w.  j a va 2 s.c  om*/
                "4 or 5 arguments required: QUERY_DIR, RESOURCE_URL, WARM_UP_ROUNDS, TEST_ROUNDS, RESULT_DIR (optional).");
        return;
    }

    File queryDir = new File(args[0]);
    String resourceUrl = args[1];
    int warmUpRounds = Integer.parseInt(args[2]);
    int testRounds = Integer.parseInt(args[3]);
    File resultDir;
    if (args.length == 4) {
        resultDir = null;
    } else {
        resultDir = new File(args[4]);
        if (!resultDir.exists()) {
            if (!resultDir.mkdirs()) {
                throw new RuntimeException("Failed to create result directory: " + resultDir);
            }
        }
    }

    File[] queryFiles = queryDir.listFiles();
    assert queryFiles != null;
    Arrays.sort(queryFiles);

    try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
        HttpPost httpPost = new HttpPost(resourceUrl);
        httpPost.addHeader("content-type", "application/json");

        for (File queryFile : queryFiles) {
            StringBuilder stringBuilder = new StringBuilder();
            try (BufferedReader bufferedReader = new BufferedReader(new FileReader(queryFile))) {
                int length;
                while ((length = bufferedReader.read(CHAR_BUFFER)) > 0) {
                    stringBuilder.append(new String(CHAR_BUFFER, 0, length));
                }
            }
            String query = stringBuilder.toString();
            httpPost.setEntity(new StringEntity(query));

            System.out.println(
                    "--------------------------------------------------------------------------------");
            System.out.println("Running query: " + query);
            System.out.println(
                    "--------------------------------------------------------------------------------");

            // Warm-up Rounds
            System.out.println("Run " + warmUpRounds + " times to warm up...");
            for (int i = 0; i < warmUpRounds; i++) {
                CloseableHttpResponse httpResponse = httpClient.execute(httpPost);
                httpResponse.close();
                System.out.print('*');
            }
            System.out.println();

            // Test Rounds
            System.out.println("Run " + testRounds + " times to get response time statistics...");
            long[] responseTimes = new long[testRounds];
            long totalResponseTime = 0L;
            for (int i = 0; i < testRounds; i++) {
                long startTime = System.currentTimeMillis();
                CloseableHttpResponse httpResponse = httpClient.execute(httpPost);
                httpResponse.close();
                long responseTime = System.currentTimeMillis() - startTime;
                responseTimes[i] = responseTime;
                totalResponseTime += responseTime;
                System.out.print(responseTime + "ms ");
            }
            System.out.println();

            // Store result.
            if (resultDir != null) {
                File resultFile = new File(resultDir, queryFile.getName() + ".result");
                CloseableHttpResponse httpResponse = httpClient.execute(httpPost);
                try (BufferedInputStream bufferedInputStream = new BufferedInputStream(
                        httpResponse.getEntity().getContent());
                        BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(resultFile))) {
                    int length;
                    while ((length = bufferedInputStream.read(BYTE_BUFFER)) > 0) {
                        bufferedWriter.write(new String(BYTE_BUFFER, 0, length));
                    }
                }
                httpResponse.close();
            }

            // Process response times.
            double averageResponseTime = (double) totalResponseTime / testRounds;
            double temp = 0;
            for (long responseTime : responseTimes) {
                temp += (responseTime - averageResponseTime) * (responseTime - averageResponseTime);
            }
            double standardDeviation = Math.sqrt(temp / testRounds);
            System.out.println("Average response time: " + averageResponseTime + "ms");
            System.out.println("Standard deviation: " + standardDeviation);
        }
    }
}