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.PostUTF8MO.java

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

    String URL = "https://sms-staging.twitter.com/receive/cloudhopper";

    // this is a Euro currency symbol
    //String text = "\u20AC";

    // shorter arabic
    //String text = "\u0623\u0647\u0644\u0627";

    // even longer arabic
    //String text = "\u0623\u0647\u0644\u0627\u0020\u0647\u0630\u0647\u0020\u0627\u0644\u062a\u062c\u0631\u0628\u0629\u0020\u0627\u0644\u0623\u0648\u0644\u0649";

    String text = "";
    for (int i = 0; i < 140; i++) {
        text += "\u0623";
    }/* w  w  w  .  jav  a 2s  . c om*/

    String srcAddr = "+14159129228";

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

    //text += " " + ticketId;

    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("  <ticketId>" + ticketId + "</ticketId>\n")
            .append("  <operatorId>" + operatorId + "</operatorId>\n")
            .append("  <sourceAddress type=\"international\">" + srcAddr + "</sourceAddress>\n")
            .append("  <destinationAddress type=\"network\">40404</destinationAddress>\n")
            .append("  <text encoding=\"UTF-8\">" + HexUtil.toHexString(text.getBytes("UTF-8")) + "</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 {
        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:PostMethodMyExample.java

public static void main(String[] args) throws Exception {
    BasicCookieStore cookieStore = new BasicCookieStore();
    CloseableHttpClient httpclient = HttpClients.custom().setDefaultCookieStore(cookieStore).build();
    try {/*from ww w.ja v  a  2 s .c o m*/
        HttpGet httpget = new HttpGet("https://portal.sun.com/portal/dt");

        CloseableHttpResponse response1 = httpclient.execute(httpget);
        try {
            HttpEntity entity = response1.getEntity();

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

            System.out.println("Initial set of cookies:");
            List<Cookie> cookies = cookieStore.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 {
            response1.close();
        }

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

        CloseableHttpResponse response2 = httpclient.execute(httpost);
        try {
            HttpEntity entity = response2.getEntity();

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

            System.out.println("Post logon cookies:");
            List<Cookie> cookies = cookieStore.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 {
            response2.close();
        }
    } finally {
        httpclient.close();
    }
}

From source file:DruidThroughput.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//from w  ww.jav  a2s . c o  m
            public void run() {
                try (CloseableHttpClient client = HttpClients.createDefault()) {
                    HttpPost post = new HttpPost("http://localhost:8082/druid/v2/?pretty");
                    post.addHeader("content-type", "application/json");
                    CloseableHttpResponse res;
                    while (true) {
                        try (BufferedReader reader = new BufferedReader(new FileReader(
                                QUERY_FILE_DIR + File.separator + random.nextInt(numQueries) + ".json"))) {
                            int length = reader.read(BUFFER);
                            post.setEntity(new StringEntity(new String(BUFFER, 0, length)));
                        }
                        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.cloudhopper.sxmp.DeliverMain.java

static public void main(String[] args) throws Exception {
    // create a deliver request
    DeliverRequest deliver = new DeliverRequest();

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

    deliver.setOperatorId(2);/*from   w  ww . j a  v  a2  s.c  o m*/

    MobileAddress sourceAddr = new MobileAddress();
    sourceAddr.setAddress(MobileAddress.Type.INTERNATIONAL, "+13135551212");
    deliver.setSourceAddress(sourceAddr);

    MobileAddress destAddr = new MobileAddress();
    destAddr.setAddress(MobileAddress.Type.NETWORK, "55555");
    deliver.setDestinationAddress(destAddr);

    deliver.setText(
            "This is a new message that I want to send that's a little larger than normal &!#@%20*()$#@!~");

    // target url
    //String url = "http://localhost:9080/api/sxmp/1.0";
    //String url = "http://lyn-stratus-001/api/sxmp/1.0";
    //String url = "http://localhost:9080/api/sxmp/1.0";
    //String strURL = "http://sfd-twtr-gw.cloudhopper.com/api/sxmp/1.0";
    String url = "http://lyn-stratus-lab5:9080/api/sxmp/1.0";

    // 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);

    // convert request into a byte array
    //byte[] data = SxmpWriter.createByteArray(submit);

    //logger.debug(StringUtil.toHexString(data));

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

    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(deliver));
            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:httpclient.client.ClientFormLogin.java

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

    // prepare parameters
    HttpParams params = new BasicHttpParams();
    HttpProtocolParams.setUserAgent(params, Constants.BROWSER_TYPE);
    HttpProtocolParams.setUseExpectContinue(params, true);
    DefaultHttpClient httpclient = new DefaultHttpClient(params);

    String loginURL = "http://10.1.1.251/login.asp";
    HttpGet httpget = new HttpGet(loginURL);
    HttpResponse response = httpclient.execute(httpget);
    HttpEntity entity = response.getEntity();
    if (entity != null) {
        entity.consumeContent();/*from w ww .  j  a  va2 s.c  o m*/
    }
    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(loginURL);
    List<NameValuePair> nvps = new ArrayList<NameValuePair>();
    nvps.add(new BasicNameValuePair("name", "fangdj"));
    nvps.add(new BasicNameValuePair("passwd", "1111"));

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

    response = httpclient.execute(httpost);
    entity = response.getEntity();
    for (Header h : response.getAllHeaders()) {
        System.out.println(h);
    }
    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());
        }
    }

    String mainURL = "http://10.1.1.251/ONWork/Record_save.asp";

    HttpPost mainHttPost = new HttpPost(mainURL);
    List<NameValuePair> mainNvps = new ArrayList<NameValuePair>();
    mainNvps.add(new BasicNameValuePair("EMP_NO", "13028"));
    mainNvps.add(new BasicNameValuePair("pwd", "1111"));
    mainNvps.add(new BasicNameValuePair("cmd2", "Apply"));

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

    response = httpclient.execute(mainHttPost);
    System.out.println(Tools.InputStreamToString(response.getEntity().getContent()));
    // 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:zz.pseas.ghost.login.weibo.WeibocnLogin.java

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

    // ?URL/*w  w w  .  j ava2 s .c om*/
    String Loginurl = "http://login.weibo.cn/login/";
    String firstpage = "http://weibo.cn/?vt=4"; // ??
    String loginnum = "test";
    String loginpwd = "test";

    CloseableHttpClient httpclient = HttpClients.createDefault(); // 
    HttpGet httpget = new HttpGet(Loginurl);

    try {
        CloseableHttpResponse response = httpclient.execute(httpget);

        String responhtml = null;
        try {
            responhtml = EntityUtils.toString(response.getEntity());
            // System.out.println(responhtml);
        } catch (IOException e1) {
            e1.printStackTrace();
        }

        // vk?,splithtml,??
        String vk = responhtml.split("<input type=\"hidden\" name=\"vk\" value=\"")[1].split("\" /><input")[0];
        System.out.println(vk);

        String pass = vk.split("_")[0];
        String finalpass = "password_" + pass;
        System.out.println(finalpass);
        response.close();

        List<BasicNameValuePair> pairs = new ArrayList<BasicNameValuePair>();
        pairs.add(new BasicNameValuePair("mobile", loginnum));
        pairs.add(new BasicNameValuePair(finalpass, loginpwd));
        pairs.add(new BasicNameValuePair("remember", "on"));
        pairs.add(new BasicNameValuePair("vk", vk));

        UrlEncodedFormEntity entity = new UrlEncodedFormEntity(pairs, Consts.UTF_8); // 
        HttpPost httppost = new HttpPost(Loginurl);
        httppost.setEntity(entity);
        // ???
        CloseableHttpResponse response2 = httpclient.execute(httppost);
        System.out.println(response2.getStatusLine().toString());
        httpclient.execute(httppost); // ?
        System.out.println("success");

        HttpGet getinfo = new HttpGet("http://m.weibo.cn/p/100803?vt=4");
        CloseableHttpResponse res;
        res = httpclient.execute(getinfo);
        System.out.println("??:");
        // ?html
        System.out.println(EntityUtils.toString(res.getEntity()));
        res.close();

    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            httpclient.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

From source file:ATTHackPause.Main.java

public static void main(String[] args) throws Exception {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    try {//w w  w  .  j a va  2s.c om
        HttpGet httpGet = new HttpGet(
                "https://api-m2x.att.com/v2/devices/ecbcc13b43417c6d9e1dc7618bbb1e6c/streams/");
        CloseableHttpResponse response1 = httpclient.execute(httpGet);
        // The underlying HTTP connection is still held by the response object
        // to allow the response content to be streamed directly from the network socket.
        // In order to ensure correct deallocation of system resources
        // the user MUST call CloseableHttpResponse#close() from a finally clause.
        // Please note that if response content is not fully consumed the underlying
        // connection cannot be safely re-used and will be shut down and discarded
        // by the connection manager.
        try {
            System.out.println(response1.getStatusLine());
            HttpEntity entity1 = response1.getEntity();
            // do something useful with the response body
            // and ensure it is fully consumed
            EntityUtils.consume(entity1);
        } finally {
            response1.close();
        }

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

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

        httpPost.setHeader("Content-type", "application/json");
        httpPost.setHeader("X-M2X-KEY", "20bfa4a4f5ed88f94d772e8389e9a6d0");
        CloseableHttpResponse response2 = httpclient.execute(httpPost);

        try {
            System.out.println(response2.getStatusLine());
            HttpEntity entity2 = response2.getEntity();
            // do something useful with the response body
            // and ensure it is fully consumed
            EntityUtils.consume(entity2);
        } finally {
            response2.close();
        }
    } finally {
        httpclient.close();
    }
}

From source file:isc_415_practica_1.ISC_415_Practica_1.java

/**
 * @param args the command line arguments
 *///from   w  ww.j  a  va 2s . c  o m
public static void main(String[] args) {
    String urlString;
    Scanner input = new Scanner(System.in);
    Document doc;

    try {
        urlString = input.next();
        if (urlString.equals("servlet")) {
            urlString = "http://localhost:8084/ISC_415_Practica1_Servlet/client";
        }
        urlString = urlString.contains("http://") || urlString.contains("https://") ? urlString
                : "http://" + urlString;
        doc = Jsoup.connect(urlString).get();
    } catch (Exception ex) {
        System.out.println("El URL ingresado no es valido.");
        return;
    }

    ArrayList<NameValuePair> formInputParams;
    formInputParams = new ArrayList<>();
    String[] plainTextDoc = new TextNode(doc.html(), "").getWholeText().split("\n");
    System.out.println(String.format("Nmero de lineas del documento: %d", plainTextDoc.length));
    System.out.println(String.format("Nmero de p tags: %d", doc.select("p").size()));
    System.out.println(String.format("Nmero de img tags: %d", doc.select("img").size()));
    System.out.println(String.format("Nmero de form tags: %d", doc.select("form").size()));

    Integer index = 1;

    ArrayList<NameValuePair> urlParameters = new ArrayList<>();
    for (Element e : doc.select("form")) {
        System.out.println(String.format("Form %d: Nmero de Input tags %d", index, e.select("input").size()));
        System.out.println(e.select("input"));

        for (Element formInput : e.select("input")) {
            if (formInput.attr("id") != null && formInput.attr("id") != "") {
                urlParameters.add(new BasicNameValuePair(formInput.attr("id"), "PRACTICA1"));
            } else if (formInput.attr("name") != null && formInput.attr("name") != "") {
                urlParameters.add(new BasicNameValuePair(formInput.attr("name"), "PRACTICA1"));
            }
        }

        index++;
    }

    if (!urlParameters.isEmpty()) {
        try {
            CloseableHttpClient httpclient = HttpClients.createDefault();
            UrlEncodedFormEntity entity = new UrlEncodedFormEntity(urlParameters, Consts.UTF_8);
            HttpPost httpPost = new HttpPost(urlString);
            httpPost.setHeader("User-Agent", USER_AGENT);
            httpPost.setEntity(entity);
            HttpResponse response = httpclient.execute(httpPost);
            System.out.println(response.getStatusLine());
        } catch (IOException ex) {
            Logger.getLogger(ISC_415_Practica_1.class.getName()).log(Level.SEVERE, null, ex);
        }

    }

}

From source file:com.luqili.http.ssl.ClientCustomSSL.java

public final static void main(String[] args) throws Exception {
    String sslKeyStorePath = "/mnt/data2/clientkey/370900.pfx";
    String sslKeyStorePassword = "370900";
    String sslKeyStoreType = "PKCS12"; // JKS PKCS12
    String sslTrustStore = "/mnt/data2/clientkey/PengeSoftOARoot.cer";
    String sslTrustStorePassword = "";
    String url = "https://123.57.205.217:8082/Service/UpReportInfoServiceSvr.assx/UpReportInfo";
    String content = "Token=&CityCodes=370900&CountyCodes=&DealDate=2016-06-16T00:00:00&Reportor=?&NewBusinessArea=1000.88&NewBusinessAmount=9898&NewHouseArea=5000&NewHouseAmount=8000&NewHouseCount=20&OldReportor=?&OldBusinessArea=1234.56&OldBusinessAmount=80000&OldHouseArea=12580&OldHouseAmount=99999&OldHouseCount=100";
    // Trust own CA and all self-signed certs
    SSLContext sslcontext = SSLContexts.custom()
            .loadTrustMaterial(new File(sslKeyStorePath), sslKeyStorePassword.toCharArray(),
                    new TrustSelfSignedStrategy())
            .loadKeyMaterial(new File(sslKeyStorePath), sslKeyStorePassword.toCharArray(),
                    sslKeyStorePassword.toCharArray())
            .build();// w w  w. j av  a 2  s.  c o  m
    // Allow TLSv1 protocol only
    SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new String[] { "TLSv1" },
            null, SSLConnectionSocketFactory.getDefaultHostnameVerifier());
    CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
    try {

        HttpPost httppost = new HttpPost(url);

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

        CloseableHttpResponse response = httpclient.execute(httppost);
        try {
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                String result = EntityUtils.toString(entity, "UTF-8").trim();
                if (!"True".toUpperCase().equals(result.toUpperCase())) {
                    System.out.println(result);
                }
            }

            System.out.println(response.getStatusLine());
            EntityUtils.consume(entity);
        } finally {
            response.close();
        }
    } finally {
        httpclient.close();
    }
}

From source file:com.client.SoapClientApache.java

public static void main(String[] args) throws Exception {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    try {//w w  w .  j a va  2 s  .c  o  m
        HttpGet httpGet = new HttpGet("http://google.com/");
        CloseableHttpResponse response1 = httpclient.execute(httpGet);
        // The underlying HTTP connection is still held by the response object
        // to allow the response content to be streamed directly from the network socket.
        // In order to ensure correct deallocation of system resources
        // the user MUST either fully consume the response content  or abort request
        // execution by calling CloseableHttpResponse#close().

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

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

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

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

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

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

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

            //                entity2.writeTo(System.out);

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

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

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