Example usage for org.apache.http.client.methods HttpPost HttpPost

List of usage examples for org.apache.http.client.methods HttpPost HttpPost

Introduction

In this page you can find the example usage for org.apache.http.client.methods HttpPost HttpPost.

Prototype

public HttpPost(final String uri) 

Source Link

Usage

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

public static void main(String[] args) {
    try {//  ww w. ja va 2s . c o  m
        File image = new File("2008-05-8 ChrisMikeNinaGrad.jpg");
        byte[] bytes = new byte[(int) image.length()];
        FileInputStream fis = new FileInputStream(image);

        int offset = 0;
        int numRead = 0;
        while (offset < bytes.length && (numRead = fis.read(bytes, offset, bytes.length - offset)) >= 0) {
            offset += numRead;
        }

        fis.close();

        HttpClient c = new DefaultHttpClient();
        HttpPost post = new HttpPost(
                "http://afrl-gift.dre.vanderbilt.edu:8080/vandyupon/events/?type=eventimagepost&eventid=2"
                        + "&time=" + System.currentTimeMillis() + "&resp=xml");

        post.addHeader("Content-Type", "image/jpeg");
        ByteArrayEntity bae = new ByteArrayEntity(bytes);
        post.setEntity(bae);

        try {
            HttpResponse resp = c.execute(post);
            resp.getEntity().writeTo(System.out);
        } catch (IOException e) {
            e.printStackTrace();
        }

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

From source file:com.dlmu.heipacker.crawler.examples.entity.mime.ClientMultipartFormPost.java

public static void main(String[] args) throws Exception {
    if (args.length != 1) {
        System.out.println("File path not given");
        System.exit(1);//from w ww.  ja v  a 2 s .c o  m
    }
    HttpClient httpclient = new DefaultHttpClient();
    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");

        MultipartEntity reqEntity = new MultipartEntity();
        reqEntity.addPart("bin", bin);
        reqEntity.addPart("comment", comment);

        httppost.setEntity(reqEntity);

        System.out.println("executing request " + httppost.getRequestLine());
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity resEntity = response.getEntity();

        System.out.println("----------------------------------------");
        System.out.println(response.getStatusLine());
        if (resEntity != null) {
            System.out.println("Response content length: " + resEntity.getContentLength());
        }
        EntityUtils.consume(resEntity);
    } finally {
        try {
            httpclient.getConnectionManager().shutdown();
        } catch (Exception ignore) {
        }
    }
}

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);//from w ww . ja  v a2 s . 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());
            }
            EntityUtils.consume(resEntity);
        } finally {
            response.close();
        }
    } finally {
        httpclient.close();
    }
}

From source file:com.oocl.euc.ita.test.QuickStart.java

public static void main(String[] args) throws Exception {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    try {//  w  ww . j a  va 2s . co  m

        //           HttpPost?
        HttpPost httpPost = new HttpPost("http://localhost:8080/qb-webapp/login");
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair("username", "Neolarry"));
        nvps.add(new BasicNameValuePair("password", "123456789"));
        httpPost.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8"));
        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();
        }

        HttpGet httpGet = new HttpGet("http://localhost:8080/qb-webapp/api/trainer");
        System.out.println(httpGet.getURI());
        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("get: "+response1.getStatusLine());
            HttpEntity entity1 = response1.getEntity();
            // do something useful with the response body
            // and ensure it is fully consumed
            String responseString = "";

            if (entity1 != null) {
                //     
                //                    System.out.println("Response content length: " + entity1.getContentLength());  
                System.out.println(responseString = EntityUtils.toString(entity1));
                // ?                      
            }

            //JsonToObject
            //              JSONArray s = JSONArray.parseArray(responseString);
            //              for (int i = 0; i < s.size(); i++) {
            //                 System.out.println(s.get(i));
            //              }

            EntityUtils.consume(entity1);
        } finally {
            response1.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);/*from   w w  w . j  av  a2s  .  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:org.corfudb.sharedlog.examples.ConfigClnt.java

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

    DefaultHttpClient httpclient = new DefaultHttpClient();
    final BufferedReader prompt = new BufferedReader(new InputStreamReader(System.in));

    CorfuConfiguration C = null;/* w  ww  . ja  v  a 2  s. c  om*/

    while (true) {

        System.out.print("> ");
        String line = prompt.readLine();
        if (line.startsWith("get")) {

            HttpGet httpget = new HttpGet("http://localhost:8000/corfu");

            System.out.println("Executing request: " + httpget.getRequestLine());
            HttpResponse response = (HttpResponse) httpclient.execute(httpget);

            System.out.println("----------------------------------------");
            System.out.println(response.getStatusLine());
            // response.getEntity().writeTo(System.out);
            // System.out.println();
            // System.out.println("----------------------------------------");

            C = new CorfuConfiguration(response.getEntity().getContent());
        } else {

            if (C == null) {
                System.out.println("configuration not set yet!");
                continue;
            }

            HttpPost httppost = new HttpPost("http://localhost:8000/corfu");
            httppost.setEntity(new StringEntity(C.ConfToXMLString()));

            System.out.println("Executing request: " + httppost.getRequestLine());
            HttpResponse response = httpclient.execute(httppost);

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

        }
    }
    // 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. ja v a  2s  .  c  o  m
        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.javaquery.aws.elasticsearch.BulkAddUpdateExample.java

public static void main(String[] args) throws UnsupportedEncodingException {
    /**/*  ww  w .  j ava 2  s.  c  om*/
     * Amazon ElasticSearch Service URL:
     * endpoint + / + {index_name} + / + _bulk
     */
    String elastic_search_url = "http://xxxxx-yyyyy-r6nvlhpscgdwms5.ap-northeast-1.es.amazonaws.com/inventory/_bulk";

    /**
     * Records to add in elastic search
     * Important Note: For elastic search bulk add and update, it should be in following format.
     * 
     * {header} + {new_line} // Header for next line json document
     * {jsonDocument} + {new_line}
     * {header} + {new_line}
     * {jsonDocument} + {new_line}
     * 
     * New line at the end of String is compulsory.
     */
    String header_one = "{\"index\":{\"_index\":\"inventory\",\"_type\":\"simple\",\"_id\":\"123\"}}\n";
    String jsonDocument_one = "{\"id\": \"123\", \"name\": \"Apple iPhone 6s\", \"stock\" : 10}\n";
    String header_two = "{\"index\":{\"_index\":\"inventory\",\"_type\":\"simple\",\"_id\":\"456\"}}\n";
    String jsonDocument_two = "{\"id\": \"456\", \"name\": \"Apple iPhone 5s\", \"stock\" : 15}\n";

    String jsonDocumentBulk = header_one + jsonDocument_one + header_two + jsonDocument_two;

    /* Convert jsonDocument to apache StringEntity */
    StringEntity payload = new StringEntity(jsonDocumentBulk);

    /* Prepare post request to add record */
    HttpPost httpPost = new HttpPost(elastic_search_url);
    /* Attach payload */
    httpPost.setEntity(payload);
    /* Execute post request */
    httpPostRequest(httpPost);
}

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   w  ww .  j  a v  a  2  s .c  o  m
                "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. j  ava2 s  .co  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);
        }
    }
}