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:com.cloudhopper.sxmp.PostMO.java

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

    String URL = "https://sms.twitter.com/receive/cloudhopper";
    String text = "HELP";
    String srcAddr = "+16504304922";

    String ticketId = System.currentTimeMillis() + "";
    String operatorId = "20";

    StringBuilder string0 = new StringBuilder(200).append("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n")
            .append("<operation type=\"deliver\">\n")
            .append(" <account username=\"customer1\" password=\"password1\"/>\n").append(" <deliverRequest>\n")
            .append("  <operatorId>" + operatorId + "</operatorId>\n")
            .append("  <sourceAddress type=\"international\">" + srcAddr + "</sourceAddress>\n")
            .append("  <destinationAddress type=\"network\">40404</destinationAddress>\n")
            .append("  <text encoding=\"ISO-8859-1\">" + HexUtil.toHexString(text.getBytes()) + "</text>\n")
            .append(" </deliverRequest>\n").append("</operation>\n").append("");

    HttpClient client = new DefaultHttpClient();
    client.getParams().setBooleanParameter("http.protocol.expect-continue", false);

    long start = System.currentTimeMillis();

    // execute request
    try {//from   ww w.  j a  v a 2s.  c om
        HttpPost post = new HttpPost(URL);

        StringEntity entity = new StringEntity(string0.toString(), "ISO-8859-1");
        entity.setContentType("text/xml; charset=\"ISO-8859-1\"");
        post.setEntity(entity);

        ResponseHandler<String> responseHandler = new BasicResponseHandler();

        String responseBody = client.execute(post, responseHandler);

        logger.debug("----------------------------------------");
        logger.debug(responseBody);
        logger.debug("----------------------------------------");
    } finally {
        // do nothing
    }

    long end = System.currentTimeMillis();

    logger.debug("Response took " + (end - start) + " ms");

}

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  ava  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);
        }
    }
}

From source file:com.tianya.ClientMultipartFormPost.java

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

    /*/*  w ww  .j  a v  a  2  s .  c  o  m*/
     if (args.length != 1)  {
    System.out.println("File path not given");
    System.exit(1);
     }
     */

    HttpClient httpclient = new DefaultHttpClient();
    String posturl = "http://letushow.com/submit";

    preGet(httpclient);

    try {
        HttpPost httppost = new HttpPost(posturl);

        FileBody bin = new FileBody(new File("/Users/gypsai/Desktop/letushow/let.gif"));
        StringBody title = new StringBody("let");

        MultipartEntity reqEntity = new MultipartEntity();
        reqEntity.addPart("imgfile", bin);
        reqEntity.addPart("csrf_token", new StringBody(csrf_token));
        reqEntity.addPart("title", title);
        reqEntity.addPart("type", new StringBody("local"));

        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());
            System.out.println(iotostring(response.getEntity().getContent()));
        }
        EntityUtils.consume(resEntity);
    } finally {
        try {
            httpclient.getConnectionManager().shutdown();
        } catch (Exception ignore) {
        }
    }
}

From source file:ClientWithResponseHandlerPost.java

public final static void main(String[] args) throws Exception {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    try {/* ww w.j a  va2 s . com*/
        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:DruidResponseTime.java

public static void main(String[] args) throws Exception {
    try (CloseableHttpClient client = HttpClients.createDefault()) {
        HttpPost post = new HttpPost("http://localhost:8082/druid/v2/?pretty");
        post.addHeader("content-type", "application/json");
        CloseableHttpResponse res;//from   w  w  w .  ja  v a 2  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("{" + "\"queryType\":\"timeseries\","
                + "\"dataSource\":\"tpch_lineitem\"," + "\"intervals\":[\"1992-01-01/1999-01-01\"],"
                + "\"granularity\":\"all\"," + "\"aggregations\":[{\"type\":\"count\",\"name\":\"count\"}]}"));
        while (true) {
            System.out.print('*');
            res = client.execute(post);
            boolean valid;
            try (BufferedInputStream in = new BufferedInputStream(res.getEntity().getContent())) {
                length = in.read(BYTE_BUFFER);
                valid = new String(BYTE_BUFFER, 0, length, "UTF-8").contains("\"count\" : 6001215");
            }
            res.close();
            if (valid) {
                break;
            } else {
                Thread.sleep(5000);
            }
        }
        System.out.println("Number of Records Test Passed");

        for (int i = 0; i < QUERIES.length; i++) {
            System.out.println(
                    "--------------------------------------------------------------------------------");
            System.out.println("Start running query: " + QUERIES[i]);
            try (BufferedReader reader = new BufferedReader(
                    new FileReader(QUERY_FILE_DIR + File.separator + i + ".json"))) {
                length = reader.read(CHAR_BUFFER);
                post.setEntity(new StringEntity(new String(CHAR_BUFFER, 0, length)));
            }

            // 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);
                res.close();
                System.out.print('*');
            }
            System.out.println();

            // Test Rounds
            int[] time = new int[TEST_ROUND];
            int totalTime = 0;
            System.out.println("Run " + TEST_ROUND + " times to get average time...");
            for (int j = 0; j < TEST_ROUND; j++) {
                long startTime = System.currentTimeMillis();
                res = client.execute(post);
                long endTime = System.currentTimeMillis();
                if (STORE_RESULT && j == 0) {
                    try (BufferedInputStream in = new BufferedInputStream(res.getEntity().getContent());
                            BufferedWriter writer = new BufferedWriter(
                                    new FileWriter(RESULT_DIR + File.separator + i + ".json", false))) {
                        while ((length = in.read(BYTE_BUFFER)) > 0) {
                            writer.write(new String(BYTE_BUFFER, 0, length, "UTF-8"));
                        }
                    }
                }
                res.close();
                time[j] = (int) (endTime - startTime);
                totalTime += time[j];
                System.out.print(time[j] + "ms ");
            }
            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:com.linkedin.pinotdruidbenchmark.PinotThroughput.java

@SuppressWarnings("InfiniteLoopStatement")
public static void main(String[] args) throws Exception {
    if (args.length != 3 && args.length != 4) {
        System.err.println(/*  www  .  j ava2  s. com*/
                "3 or 4 arguments required: QUERY_DIR, RESOURCE_URL, NUM_CLIENTS, TEST_TIME (seconds).");
        return;
    }

    File queryDir = new File(args[0]);
    String resourceUrl = args[1];
    final int numClients = Integer.parseInt(args[2]);
    final long endTime;
    if (args.length == 3) {
        endTime = Long.MAX_VALUE;
    } else {
        endTime = System.currentTimeMillis() + Integer.parseInt(args[3]) * MILLIS_PER_SECOND;
    }

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

    final int numQueries = queryFiles.length;
    final HttpPost[] httpPosts = new HttpPost[numQueries];
    for (int i = 0; i < numQueries; i++) {
        HttpPost httpPost = new HttpPost(resourceUrl);
        String query = new BufferedReader(new FileReader(queryFiles[i])).readLine();
        httpPost.setEntity(new StringEntity("{\"pql\":\"" + query + "\"}"));
        httpPosts[i] = httpPost;
    }

    final AtomicInteger counter = new AtomicInteger(0);
    final AtomicLong totalResponseTime = new AtomicLong(0L);
    final ExecutorService executorService = Executors.newFixedThreadPool(numClients);

    for (int i = 0; i < numClients; i++) {
        executorService.submit(new Runnable() {
            @Override
            public void run() {
                try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
                    while (System.currentTimeMillis() < endTime) {
                        long startTime = System.currentTimeMillis();
                        CloseableHttpResponse httpResponse = httpClient
                                .execute(httpPosts[RANDOM.nextInt(numQueries)]);
                        httpResponse.close();
                        long responseTime = System.currentTimeMillis() - startTime;
                        counter.getAndIncrement();
                        totalResponseTime.getAndAdd(responseTime);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
    }
    executorService.shutdown();

    long startTime = System.currentTimeMillis();
    while (System.currentTimeMillis() < endTime) {
        Thread.sleep(REPORT_INTERVAL_MILLIS);
        double timePassedSeconds = ((double) (System.currentTimeMillis() - startTime)) / MILLIS_PER_SECOND;
        int count = counter.get();
        double avgResponseTime = ((double) totalResponseTime.get()) / count;
        System.out.println("Time Passed: " + timePassedSeconds + "s, Query Executed: " + count + ", QPS: "
                + count / timePassedSeconds + ", Avg Response Time: " + avgResponseTime + "ms");
    }
}

From source file:com.dlmu.heipacker.crawler.client.QuickStart.java

public static void main(String[] args) throws Exception {
    DefaultHttpClient httpclient = new DefaultHttpClient();
    HttpGet httpGet = new HttpGet("http://targethost/homepage");

    HttpResponse 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 HttpGet#releaseConnection().

    try {/*from w w w . j av a 2s.c o  m*/
        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 {
        httpGet.releaseConnection();
    }

    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));
    HttpResponse 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 {
        httpPost.releaseConnection();
    }
}

From source file:se.vgregion.pubsub.inttest.SubscriberRunner.java

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

    LocalTestServer server = new LocalTestServer(null, null);

    server.register("/*", new HttpRequestHandler() {
        @Override/*from   w w  w. j  a  va2  s  . c om*/
        public void handle(HttpRequest request, HttpResponse response, HttpContext context)
                throws HttpException, IOException {
            String challenge = getQueryParamValue(request.getRequestLine().getUri(), "hub.challenge");

            if (challenge != null) {
                // subscription verification, confirm
                System.out.println("Respond to challenge");
                response.setEntity(new StringEntity(challenge));
            } else if (request instanceof HttpEntityEnclosingRequest) {
                HttpEntity entity = ((HttpEntityEnclosingRequest) request).getEntity();
                //                    System.out.println(HttpUtil.readContent(entity));
            } else {
                System.err.println("Unknown request");
            }
        }
    });
    server.start();

    HttpPost post = new HttpPost("http://localhost:8080/");

    List<NameValuePair> parameters = new ArrayList<NameValuePair>();
    parameters.add(new BasicNameValuePair("hub.callback", buildTestUrl(server, "/").toString()));
    parameters.add(new BasicNameValuePair("hub.mode", "subscribe"));
    parameters.add(new BasicNameValuePair("hub.topic", "http://feeds.feedburner.com/protocol7/main"));
    parameters.add(new BasicNameValuePair("hub.verify", "sync"));

    post.setEntity(new UrlEncodedFormEntity(parameters));

    DefaultHttpClient client = new DefaultHttpClient();
    client.execute(post);
}

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

@SuppressWarnings("InfiniteLoopStatement")
public static void main(String[] args) throws Exception {
    if (args.length != 3 && args.length != 4) {
        System.err.println(// w w w  .j  a  v  a2s.  c  om
                "3 or 4 arguments required: QUERY_DIR, RESOURCE_URL, NUM_CLIENTS, TEST_TIME (seconds).");
        return;
    }

    File queryDir = new File(args[0]);
    String resourceUrl = args[1];
    final int numClients = Integer.parseInt(args[2]);
    final long endTime;
    if (args.length == 3) {
        endTime = Long.MAX_VALUE;
    } else {
        endTime = System.currentTimeMillis() + Integer.parseInt(args[3]) * MILLIS_PER_SECOND;
    }

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

    final int numQueries = queryFiles.length;
    final HttpPost[] httpPosts = new HttpPost[numQueries];
    for (int i = 0; i < numQueries; i++) {
        HttpPost httpPost = new HttpPost(resourceUrl);
        httpPost.addHeader("content-type", "application/json");
        StringBuilder stringBuilder = new StringBuilder();
        try (BufferedReader bufferedReader = new BufferedReader(new FileReader(queryFiles[i]))) {
            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));
        httpPosts[i] = httpPost;
    }

    final AtomicInteger counter = new AtomicInteger(0);
    final AtomicLong totalResponseTime = new AtomicLong(0L);
    final ExecutorService executorService = Executors.newFixedThreadPool(numClients);

    for (int i = 0; i < numClients; i++) {
        executorService.submit(new Runnable() {
            @Override
            public void run() {
                try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
                    while (System.currentTimeMillis() < endTime) {
                        long startTime = System.currentTimeMillis();
                        CloseableHttpResponse httpResponse = httpClient
                                .execute(httpPosts[RANDOM.nextInt(numQueries)]);
                        httpResponse.close();
                        long responseTime = System.currentTimeMillis() - startTime;
                        counter.getAndIncrement();
                        totalResponseTime.getAndAdd(responseTime);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
    }
    executorService.shutdown();

    long startTime = System.currentTimeMillis();
    while (System.currentTimeMillis() < endTime) {
        Thread.sleep(REPORT_INTERVAL_MILLIS);
        double timePassedSeconds = ((double) (System.currentTimeMillis() - startTime)) / MILLIS_PER_SECOND;
        int count = counter.get();
        double avgResponseTime = ((double) totalResponseTime.get()) / count;
        System.out.println("Time Passed: " + timePassedSeconds + "s, Query Executed: " + count + ", QPS: "
                + count / timePassedSeconds + ", Avg Response Time: " + avgResponseTime + "ms");
    }
}

From source file:com.hilatest.httpclient.apacheexample.ClientFormLogin.java

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

    DefaultHttpClient httpclient = new DefaultHttpClient();

    HttpGet httpget = new HttpGet("https://portal.sun.com/portal/dt");

    HttpResponse response = httpclient.execute(httpget);
    HttpEntity entity = response.getEntity();

    System.out.println("Login form get: " + response.getStatusLine());
    if (entity != null) {
        entity.consumeContent();//from  w  ww .  j  a va 2 s  .  c om
    }
    System.out.println("Initial set of cookies:");
    List<Cookie> cookies = httpclient.getCookieStore().getCookies();
    if (cookies.isEmpty()) {
        System.out.println("None");
    } else {
        for (int i = 0; i < cookies.size(); i++) {
            System.out.println("- " + cookies.get(i).toString());
        }
    }

    HttpPost httpost = new HttpPost("https://portal.sun.com/amserver/UI/Login?" + "org=self_registered_users&"
            + "goto=/portal/dt&" + "gotoOnFail=/portal/dt?error=true");

    List<NameValuePair> nvps = new ArrayList<NameValuePair>();
    nvps.add(new BasicNameValuePair("IDToken1", "username"));
    nvps.add(new BasicNameValuePair("IDToken2", "password"));

    httpost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));

    response = httpclient.execute(httpost);
    entity = response.getEntity();

    System.out.println("Login form get: " + response.getStatusLine());
    if (entity != null) {
        entity.consumeContent();
    }

    System.out.println("Post logon cookies:");
    cookies = httpclient.getCookieStore().getCookies();
    if (cookies.isEmpty()) {
        System.out.println("None");
    } else {
        for (int i = 0; i < cookies.size(); i++) {
            System.out.println("- " + cookies.get(i).toString());
        }
    }

    // When HttpClient instance is no longer needed, 
    // shut down the connection manager to ensure
    // immediate deallocation of all system resources
    httpclient.getConnectionManager().shutdown();
}