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.dlmu.heipacker.crawler.client.ClientFormLogin.java

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

    DefaultHttpClient httpclient = new DefaultHttpClient();
    try {/*from   ww  w. jav  a  2s .  c  o m*/
        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());
        EntityUtils.consume(entity);

        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, Consts.UTF_8));

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

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

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

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

From source file:com.mtea.macrotea_httpclient_study.ClientFormLogin.java

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

    DefaultHttpClient httpclient = new DefaultHttpClient();
    try {/*from w ww  .  j  av  a  2 s .  com*/
        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());
        //??
        EntityUtils.consume(entity);

        System.out.println("?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, "UTF-8"));

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

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

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

    } finally {
        //??httpclient???
        httpclient.getConnectionManager().shutdown();
    }
}

From source file:com.http.QuickStart.java

public static void main(String[] args) throws Exception {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    try {/*  w  w  w  .ja  va2  s .  com*/
        HttpGet httpGet = new HttpGet("http://localhost:8081/cring/jsp/user/index.jsp");
        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(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://localhost:8081/cring/jsp/user/userLogin.do?method=login");
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair("username", "057185581120"));
        nvps.add(new BasicNameValuePair("password", "111111"));
        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.cloudhopper.sxmp.SubmitMain.java

static public void main(String[] args) throws Exception {
    String url = "http://localhost:9080/api/sxmp/1.0";

    // create a submit request
    SubmitRequest submit = new SubmitRequest();

    submit.setAccount(new Account("customer1", "password1"));

    submit.setDeliveryReport(Boolean.TRUE);

    MobileAddress sourceAddr = new MobileAddress();
    sourceAddr.setAddress(MobileAddress.Type.NETWORK, "40404");
    submit.setSourceAddress(sourceAddr);

    submit.setOperatorId(24);//from  w ww  .  j  ava2 s.co m

    MobileAddress destAddr = new MobileAddress();
    destAddr.setAddress(MobileAddress.Type.INTERNATIONAL, "+14155551212");

    submit.setDestinationAddress(destAddr);

    submit.setText(
            "Test abcdefghijabcdefghijabcdefghijabcdefghijabcdefghijabcdefghijabcdefghijjabcdefghijjabcdefghijjabcdefghijjabcdefghijjabcdefghijjabcdefghijjabcdefghijbcdefghij",
            TextEncoding.UTF_8);
    //submit.setText("Hello World");

    // Get file to be posted
    HttpClient client = new DefaultHttpClient();

    client.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
    client.getParams().setParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, Boolean.FALSE);

    long totalStart = System.currentTimeMillis();
    int count = 1;

    for (int i = 0; i < count; i++) {
        long start = System.currentTimeMillis();

        // execute request
        try {
            HttpPost post = new HttpPost(url);

            //ByteArrayEntity entity = new ByteArrayEntity(data);
            StringEntity entity = new StringEntity(SxmpWriter.createString(submit));
            entity.setContentType("text/xml; charset=\"iso-8859-1\"");
            post.setEntity(entity);

            ResponseHandler<String> responseHandler = new BasicResponseHandler();

            String responseBody = client.execute(post, responseHandler);
            long stop = System.currentTimeMillis();

            logger.debug("----------------------------------------");
            logger.debug("Response took " + (stop - start) + " ms");
            logger.debug(responseBody);
            logger.debug("----------------------------------------");
        } finally {
            // do nothing
        }
    }

    long totalEnd = System.currentTimeMillis();

    logger.debug("Response took " + (totalEnd - totalStart) + " ms for " + count + " requests");

    double seconds = ((double) (totalEnd - totalStart)) / 1000;
    double smspersec = ((double) count) / seconds;
    logger.debug("SMS / Sec: " + DecimalUtil.toString(smspersec, 2));

}

From source file:PinotThroughput.java

@SuppressWarnings("InfiniteLoopStatement")
public static void main(String[] args) throws Exception {
    final int numQueries = QUERIES.length;
    final Random random = new Random(RANDOM_SEED);
    final AtomicInteger counter = new AtomicInteger(0);
    final AtomicLong totalResponseTime = new AtomicLong(0L);
    final ExecutorService executorService = Executors.newFixedThreadPool(NUM_CLIENTS);

    for (int i = 0; i < NUM_CLIENTS; i++) {
        executorService.submit(new Runnable() {
            @Override//  ww  w  . j a  v  a 2s  .c o m
            public void run() {
                try (CloseableHttpClient client = HttpClients.createDefault()) {
                    HttpPost post = new HttpPost("http://localhost:8099/query");
                    CloseableHttpResponse res;
                    while (true) {
                        String query = QUERIES[random.nextInt(numQueries)];
                        post.setEntity(new StringEntity("{\"pql\":\"" + query + "\"}"));
                        long start = System.currentTimeMillis();
                        res = client.execute(post);
                        res.close();
                        counter.getAndIncrement();
                        totalResponseTime.getAndAdd(System.currentTimeMillis() - start);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    long startTime = System.currentTimeMillis();
    while (true) {
        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.music.tools.SongDBDownloader.java

public static void main(String[] args) throws Exception {
    HttpClient client = new DefaultHttpClient();

    //        HttpHost proxy = new HttpHost("localhost", 8888);
    //        client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);

    HttpContext ctx = new BasicHttpContext();

    HttpUriRequest req = new HttpGet(
            "http://www.hooktheory.com/analysis/view/the-beatles/i-want-to-hold-your-hand");
    client.execute(req, ctx);//  w w  w  .  ja  v  a 2 s  .  c o  m
    req.abort();

    List<String> urls = getSongUrls(
            "http://www.hooktheory.com/analysis/browseSearch?sQuery=&sOrderBy=views&nResultsPerPage=525&nPage=1",
            client, ctx);
    List<List<? extends NameValuePair>> paramsList = new ArrayList<>(urls.size());
    for (String songUrl : urls) {
        paramsList.addAll(getSongParams(songUrl, client, ctx));
    }
    int i = 0;
    for (List<? extends NameValuePair> params : paramsList) {

        HttpPost request = new HttpPost("http://www.hooktheory.com/songs/getXML");

        request.setHeader("User-Agent",
                "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:15.0) Gecko/20100101 Firefox/15.0.1");
        request.setHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
        request.setHeader("Accept-Encoding", "gzip, deflate");
        request.setHeader("Accept-Language", "en,en-us;q=0.7,bg;q=0.3");
        request.setHeader("Content-Type", "application/x-www-form-urlencoded");
        request.setHeader("Origin", "http://www.hooktheory.com");
        request.setHeader("Referer",
                URLEncoder.encode("http://www.hooktheory.com/swf/DNALive Version 1.0.131.swf", "utf-8"));

        HttpEntity entity = new UrlEncodedFormEntity(params);
        request.setEntity(entity);

        try {
            HttpResponse response = client.execute(request, ctx);
            if (response.getStatusLine().getStatusCode() == 200) {
                InputStream is = response.getEntity().getContent();
                String xml = CharStreams.toString(new InputStreamReader(is));
                is.close();
                Files.write(xml, new File("c:/tmp/musicdb/" + i + ".xml"), Charset.forName("utf-8"));
            } else {
                System.out.println(response.getStatusLine());
                System.out.println(params);
            }
            i++;
            request.abort();
        } catch (Exception ex) {
            System.out.println(params);
            ex.printStackTrace();
        }
    }
}

From source file:com.cloudhopper.sxmp.demo.SubmitMain.java

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

    String url = "http://127.0.0.1:8080/api/sxmp/1.0";
    String phone = "+14155551212";
    int operator = 1;
    if (args.length > 0)
        url = args[0];/*from  ww w .j a va2 s .  co m*/
    if (args.length > 1)
        phone = args[1];
    if (args.length > 2)
        operator = Integer.parseInt(args[2]);

    // create a submit request
    SubmitRequest submit = new SubmitRequest();
    submit.setAccount(new Account("customer1", "password1"));
    submit.setDeliveryReport(Boolean.TRUE);

    MobileAddress sourceAddr = new MobileAddress();
    sourceAddr.setAddress(MobileAddress.Type.NETWORK, "40404");
    submit.setSourceAddress(sourceAddr);
    submit.setOperatorId(operator);

    submit.setPriority(Priority.URGENT);

    MobileAddress destAddr = new MobileAddress();
    destAddr.setAddress(MobileAddress.Type.INTERNATIONAL, phone);

    submit.setDestinationAddress(destAddr);
    submit.setText("Hello World");

    // Get file to be posted
    HttpClient client = new DefaultHttpClient();

    client.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
    client.getParams().setParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, Boolean.FALSE);

    long totalStart = System.currentTimeMillis();
    int count = 1;

    for (int i = 0; i < count; i++) {
        long start = System.currentTimeMillis();

        // execute request
        try {
            HttpPost post = new HttpPost(url);

            //ByteArrayEntity entity = new ByteArrayEntity(data);
            StringEntity entity = new StringEntity(SxmpWriter.createString(submit));
            entity.setContentType("text/xml; charset=\"iso-8859-1\"");
            post.setEntity(entity);

            ResponseHandler<String> responseHandler = new BasicResponseHandler();

            String responseBody = client.execute(post, responseHandler);
            long stop = System.currentTimeMillis();

            logger.debug("----------------------------------------");
            logger.debug("Response took " + (stop - start) + " ms");
            logger.debug(responseBody);
            logger.debug("----------------------------------------");
        } finally {
            // do nothing
        }
    }

    long totalEnd = System.currentTimeMillis();

    logger.debug("Response took " + (totalEnd - totalStart) + " ms for " + count + " requests");

    double seconds = ((double) (totalEnd - totalStart)) / 1000;
    double smspersec = ((double) count) / seconds;
    logger.debug("SMS / Sec: " + DecimalUtil.toString(smspersec, 2));

}

From source file:com.test.httpClient.QuickStart.java

public static void main(String[] args) throws Exception {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    try {/* w  w w  . j av  a 2  s.  c o  m*/
        HttpGet httpGet = new HttpGet("http://www.baidu.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 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://www.baidu.com");
        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:demo.test.tutorial_learn.QuickStart.java

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

From source file:com.cloverframework.core.QuickStart.java

public static void main(String[] args) throws Exception {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    try {/*from   w  w  w  .  j  a va2s  .c  o  m*/
        HttpGet httpGet = new HttpGet("http://www.sina.com.cn/");
        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://www.sina.com.cn/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();
    }
}