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

public static void main(String[] args) {
    HttpClient c = new DefaultHttpClient();
    HttpPost post = new HttpPost("http://localhost:8080/vandyupon/events/");
    post.addHeader("Content-Type", "application/x-www-form-urlencoded");

    String params = "type=eventpost&eventname=Test&starttime=" + System.currentTimeMillis() + "&endtime="
            + (System.currentTimeMillis() + 6000000)
            + "&userid=chris&resp=xml&desc=a%20new%20event&locationlat=36.1437&locationlon=-86.8046";
    post.setEntity(new ByteArrayEntity(params.toString().getBytes()));

    try {/*w w  w .j ava  2  s  .com*/
        HttpResponse resp = c.execute(post);
        resp.getEntity().writeTo(System.out);
    } catch (IOException e) {
        e.printStackTrace();
    }

}

From source file:com.anteam.demo.logback.PostDemo.java

public static void main(String[] args) {
    StringEntity stringEntity = new StringEntity("this is the log2.",
            ContentType.create("text/plain", "UTF-8"));
    HttpPost post = new HttpPost("http://10.16.0.207:9000");
    post.setEntity(stringEntity);/*from w  ww  . ja  v a2  s.co  m*/
    HttpClient httpclient = new DefaultHttpClient();

    // Execute the request
    HttpResponse response = null;
    try {
        response = httpclient.execute(post);
    } catch (ClientProtocolException e1) {
        e1.printStackTrace();
    } catch (IOException e1) {
        e1.printStackTrace();
    }

    // Examine the response status
    System.out.println(response.getStatusLine());

    // Get hold of the response entity
    HttpEntity entity = response.getEntity();

    // If the response does not enclose an entity, there is no need
    // to worry about connection release
    if (entity != null) {
        InputStream instream = null;
        try {
            instream = entity.getContent();

            BufferedReader reader = new BufferedReader(new InputStreamReader(instream));
            // do something useful with the response
            System.out.println(reader.readLine());

        } catch (Exception ex) {
            post.abort();

        } finally {

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

        }
        httpclient.getConnectionManager().shutdown();
    }
}

From source file:com.anteam.demo.httpclient.PostDemo.java

public static void main(String[] args) {
    StringEntity stringEntity = new StringEntity("this is the log2.",
            ContentType.create("text/plain", "UTF-8"));
    HttpPost post = new HttpPost("http://127.0.0.1:9000");
    post.setEntity(stringEntity);//  w ww  .  j  ava 2  s  .com
    HttpClient httpclient = new DefaultHttpClient();

    // Execute the request
    HttpResponse response = null;
    try {
        response = httpclient.execute(post);
    } catch (ClientProtocolException e1) {
        e1.printStackTrace();
    } catch (IOException e1) {
        e1.printStackTrace();
    }

    // Examine the response status
    System.out.println(response.getStatusLine());

    // Get hold of the response entity
    HttpEntity entity = response.getEntity();

    // If the response does not enclose an entity, there is no need
    // to worry about connection release
    if (entity != null) {
        InputStream instream = null;
        try {
            instream = entity.getContent();

            BufferedReader reader = new BufferedReader(new InputStreamReader(instream));
            // do something useful with the response
            System.out.println(reader.readLine());

        } catch (Exception ex) {
            post.abort();

        } finally {

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

        }
        httpclient.getConnectionManager().shutdown();
    }
}

From source file:postenergy.TestHttpClient.java

public static void main(String[] args) {
    HttpClient client = new DefaultHttpClient();
    HttpPost post = new HttpPost("https://www.google.com/accounts/ClientLogin");

    try {/*from  w  w  w. j  a va  2  s .  co  m*/

        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
        nameValuePairs.add(new BasicNameValuePair("Email", "youremail"));
        nameValuePairs.add(new BasicNameValuePair("Passwd", "yourpassword"));
        nameValuePairs.add(new BasicNameValuePair("accountType", "GOOGLE"));
        nameValuePairs.add(new BasicNameValuePair("source", "Google-cURL-Example"));
        nameValuePairs.add(new BasicNameValuePair("service", "ac2dm"));

        post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
        HttpResponse response = client.execute(post);
        BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

        String line = "";
        while ((line = rd.readLine()) != null) {
            System.out.println(line);
            if (line.startsWith("Auth=")) {
                String key = line.substring(5);
                // do something with the key
            }

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

From source file:com.javaquery.aws.elasticsearch.AddUpdateExample.java

public static void main(String[] args) throws UnsupportedEncodingException {
    /**//from www  .  j  a  v a  2  s . c  o  m
     * Amazon ElasticSearch Service URL:
     * endpoint + / + {index_name} + / + {type} + / + {id}
     */
    String elastic_search_url = "http://xxxxx-yyyyy-r6nvlhpscgdwms5.ap-northeast-1.es.amazonaws.com/inventory/simple/123";

    /* Record to add in elastic search */
    String jsonDocument = "{\"id\": \"123\", \"name\": \"Apple iPhone 6s\", \"stock\" : 10}";

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

    /* 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:de.zazaz.iot.bosch.indego.App.java

public static void main(String[] args) throws ClientProtocolException, IOException, InterruptedException {
    CloseableHttpClient httpClient = HttpClients.createDefault();

    HttpPost httpPost = new HttpPost(BASE_URL_PUSHWOOSH + "registerDevice");
    String jsonPost = ""//
            + "{" //
            + "  \"request\":{" //
            + "     \"application\":\"8FF60-0666B\"," //
            + "     \"push_token\":\"124692134091\"," //
            + "     \"hwid\":\"00-0C-29-E8-B1-8D\"," //
            + "     \"timezone\":3600," //
            + "     \"device_type\":3" //
            + "  }" //
            + "}";
    httpPost.setEntity(new StringEntity(jsonPost, ContentType.APPLICATION_JSON));
    CloseableHttpResponse response = httpClient.execute(httpPost);

    System.out.println(response.getStatusLine());
    Header[] headers = response.getAllHeaders();
    for (int i = 0; i < headers.length; i++) {
        System.out.println(headers[i].getName() + ": " + headers[i].getValue());
    }//from ww w .j  a  v a 2s.c  om
    HttpEntity entity = response.getEntity();
    String contents = EntityUtils.toString(entity);
    System.out.println(contents);

    Thread.sleep(5000);

    HttpPost httpGet = new HttpPost(BASE_URL_PUSHWOOSH + "checkMessage");
    String jsonGet = ""//
            + "{" //
            + "  \"request\":{" //
            + "     \"application\":\"8FF60-0666B\"," //
            + "     \"hwid\":\"00-0C-29-E8-B1-8D\"" //
            + "  }" //
            + "}";
    httpGet.setEntity(new StringEntity(jsonGet, ContentType.APPLICATION_JSON));
    httpClient.execute(httpGet);

    response.close();
}

From source file:org.wso2.carbon.sample.pizzadelivery.client.PizzaOrderClient.java

public static void main(String[] args) {
    KeyStoreUtil.setTrustStoreParams();//from ww w. j a  v a2  s .c om
    String url = args[0];
    boolean batchedElements = Boolean.valueOf(args[1]);

    HttpClient httpClient = new SystemDefaultHttpClient();

    try {
        HttpPost method = new HttpPost(url);

        if (httpClient != null) {
            String[] xmlElements = new String[] {
                    "<mypizza:PizzaOrderStream xmlns:mypizza=\"http://samples.wso2.org/\">\n"
                            + "        <mypizza:PizzaOrder>\n"
                            + "              <mypizza:OrderNo>0023</mypizza:OrderNo>\n"
                            + "              <mypizza:Type>PEPPERONI</mypizza:Type>\n"
                            + "              <mypizza:Size>L</mypizza:Size>\n"
                            + "              <mypizza:Quantity>2</mypizza:Quantity>\n"
                            + "              <mypizza:Contact>James Mark</mypizza:Contact>\n"
                            + "              <mypizza:Address>29BX Finchwood Ave, Clovis, CA 93611</mypizza:Address>\n"
                            + "        </mypizza:PizzaOrder>\n" + "</mypizza:PizzaOrderStream>",
                    "<mypizza:PizzaOrderStream xmlns:mypizza=\"http://samples.wso2.org/\">\n"
                            + "        <mypizza:PizzaOrder>\n"
                            + "              <mypizza:OrderNo>0024</mypizza:OrderNo>\n"
                            + "              <mypizza:Type>CHEESE</mypizza:Type>\n"
                            + "              <mypizza:Size>M</mypizza:Size>\n"
                            + "              <mypizza:Quantity>1</mypizza:Quantity>\n"
                            + "              <mypizza:Contact>Henry Clock</mypizza:Contact>\n"
                            + "              <mypizza:Address>2CYL Morris Ave, Clovis, CA 93611</mypizza:Address>\n"
                            + "        </mypizza:PizzaOrder>\n" + "</mypizza:PizzaOrderStream>",
                    "<mypizza:PizzaOrderStream xmlns:mypizza=\"http://samples.wso2.org/\">\n"
                            + "        <mypizza:PizzaOrder>\n"
                            + "              <mypizza:OrderNo>0025</mypizza:OrderNo>\n"
                            + "              <mypizza:Type>SEAFOOD</mypizza:Type>\n"
                            + "              <mypizza:Size>S</mypizza:Size>\n"
                            + "              <mypizza:Quantity>4</mypizza:Quantity>\n"
                            + "              <mypizza:Contact>James Mark</mypizza:Contact>\n"
                            + "              <mypizza:Address>22RE Robinwood Ave, Clovis, CA 93611</mypizza:Address>\n"
                            + "        </mypizza:PizzaOrder>\n" + "</mypizza:PizzaOrderStream>",
                    "<mypizza:PizzaOrderStream xmlns:mypizza=\"http://samples.wso2.org/\">\n"
                            + "        <mypizza:PizzaOrder>\n"
                            + "              <mypizza:OrderNo>0026</mypizza:OrderNo>\n"
                            + "              <mypizza:Type>CHICKEN</mypizza:Type>\n"
                            + "              <mypizza:Size>L</mypizza:Size>\n"
                            + "              <mypizza:Contact>Alis Miranda</mypizza:Contact>\n"
                            + "              <mypizza:Address>779 Burl Ave, Clovis, CA 93611</mypizza:Address>\n"
                            + "        </mypizza:PizzaOrder>\n" + "</mypizza:PizzaOrderStream>",
                    "<mypizza:PizzaOrderStream xmlns:mypizza=\"http://samples.wso2.org/\">\n"
                            + "        <mypizza:PizzaOrder>\n"
                            + "              <mypizza:OrderNo>0026</mypizza:OrderNo>\n"
                            + "              <mypizza:Type>VEGGIE</mypizza:Type>\n"
                            + "              <mypizza:Size>L</mypizza:Size>\n"
                            + "              <mypizza:Quantity>1</mypizza:Quantity>\n"
                            + "              <mypizza:Contact>James Mark</mypizza:Contact>\n"
                            + "              <mypizza:Address>29BX Finchwood Ave, Clovis, CA 93611</mypizza:Address>\n"
                            + "        </mypizza:PizzaOrder>\n" + "</mypizza:PizzaOrderStream>" };

            String[] batchedXmlElements = new String[] {
                    "<mypizza:PizzaOrderStream xmlns:mypizza=\"http://samples.wso2.org/\">\n"
                            + "        <mypizza:PizzaOrder>\n"
                            + "              <mypizza:OrderNo>0023</mypizza:OrderNo>\n"
                            + "              <mypizza:Type>PEPPERONI</mypizza:Type>\n"
                            + "              <mypizza:Size>L</mypizza:Size>\n"
                            + "              <mypizza:Quantity>2</mypizza:Quantity>\n"
                            + "              <mypizza:Contact>James Mark</mypizza:Contact>\n"
                            + "              <mypizza:Address>29BX Finchwood Ave, Clovis, CA 93611</mypizza:Address>\n"
                            + "        </mypizza:PizzaOrder>\n" + "        <mypizza:PizzaOrder>\n"
                            + "              <mypizza:OrderNo>0024</mypizza:OrderNo>\n"
                            + "              <mypizza:Type>CHEESE</mypizza:Type>\n"
                            + "              <mypizza:Size>M</mypizza:Size>\n"
                            + "              <mypizza:Quantity>1</mypizza:Quantity>\n"
                            + "              <mypizza:Contact>Henry Clock</mypizza:Contact>\n"
                            + "              <mypizza:Address>2CYL Morris Ave, Clovis, CA 93611</mypizza:Address>\n"
                            + "        </mypizza:PizzaOrder>\n" + "        <mypizza:PizzaOrder>\n"
                            + "              <mypizza:OrderNo>0025</mypizza:OrderNo>\n"
                            + "              <mypizza:Type>SEAFOOD</mypizza:Type>\n"
                            + "              <mypizza:Size>S</mypizza:Size>\n"
                            + "              <mypizza:Quantity>4</mypizza:Quantity>\n"
                            + "              <mypizza:Contact>James Mark</mypizza:Contact>\n"
                            + "              <mypizza:Address>22RE Robinwood Ave, Clovis, CA 93611</mypizza:Address>\n"
                            + "        </mypizza:PizzaOrder>\n" + "</mypizza:PizzaOrderStream>",
                    "<mypizza:PizzaOrderStream xmlns:mypizza=\"http://samples.wso2.org/\">\n"
                            + "        <mypizza:PizzaOrder>\n"
                            + "              <mypizza:OrderNo>0026</mypizza:OrderNo>\n"
                            + "              <mypizza:Type>CHICKEN</mypizza:Type>\n"
                            + "              <mypizza:Size>L</mypizza:Size>\n"
                            + "              <mypizza:Quantity>1</mypizza:Quantity>\n"
                            + "              <mypizza:Contact>Alis Miranda</mypizza:Contact>\n"
                            + "              <mypizza:Address>779 Burl Ave, Clovis, CA 93611</mypizza:Address>\n"
                            + "        </mypizza:PizzaOrder>\n" + "        <mypizza:PizzaOrder>\n"
                            + "              <mypizza:OrderNo>0026</mypizza:OrderNo>\n"
                            + "              <mypizza:Type>VEGGIE</mypizza:Type>\n"
                            + "              <mypizza:Size>L</mypizza:Size>\n"
                            + "              <mypizza:Quantity>1</mypizza:Quantity>\n"
                            + "              <mypizza:Contact>James Mark</mypizza:Contact>\n"
                            + "              <mypizza:Address>29BX Finchwood Ave, Clovis, CA 93611</mypizza:Address>\n"
                            + "        </mypizza:PizzaOrder>\n" + "</mypizza:PizzaOrderStream>" };

            int i = 0;
            if (batchedElements) {
                for (String xmlElement : batchedXmlElements) {
                    StringEntity entity = new StringEntity(xmlElement);
                    method.setEntity(entity);
                    httpClient.execute(method).getEntity().getContent().close();
                    System.out.println("Sent event no :" + i++);
                }
            } else {
                for (String xmlElement : xmlElements) {
                    StringEntity entity = new StringEntity(xmlElement);
                    method.setEntity(entity);
                    httpClient.execute(method).getEntity().getContent().close();
                    System.out.println("Sent event no :" + i++);
                }
            }
            Thread.sleep(500); // We need to wait some time for the message to be sent
        }
    } catch (Throwable t) {
        t.printStackTrace();
    }
}

From source file:com.gemini.httpclienttest.HttpClientTestMain.java

public static void main(String[] args) {
    //authenticate with the server
    URL url;/*from   w  w  w.ja  va  2s  .  c om*/
    try {
        url = new URL("http://198.11.209.34:5000/v2.0/tokens");
    } catch (MalformedURLException ex) {
        System.out.printf("Invalid Endpoint - not a valid URL {}", "http://198.11.209.34:5000/v2.0");
        return;
    }
    CloseableHttpClient httpclient = HttpClientBuilder.create().build();
    try {
        HttpPost httpPost = new HttpPost(url.toString());
        httpPost.setHeader("Content-Type", "application/json");
        StringEntity strEntity = new StringEntity(
                "{\"auth\":{\"tenantName\":\"Gemini-network-prj\",\"passwordCredentials\":{\"username\":\"sri\",\"password\":\"srikumar12\"}}}");
        httpPost.setEntity(strEntity);
        //System.out.println("Executing request " + httpget.getRequestLine());
        CloseableHttpResponse response = httpclient.execute(httpPost);
        try {
            //get the response status code 
            String respStatus = response.getStatusLine().getReasonPhrase();

            //get the response body
            int bytes = response.getEntity().getContent().available();
            InputStream body = response.getEntity().getContent();
            BufferedReader in = new BufferedReader(new InputStreamReader(body));
            String line;
            StringBuffer sbJSON = new StringBuffer();
            while ((line = in.readLine()) != null) {
                sbJSON.append(line);
            }
            String json = sbJSON.toString();
            EntityUtils.consume(response.getEntity());

            GsonBuilder gsonBuilder = new GsonBuilder();
            Object parsedJson = gsonBuilder.create().fromJson(json, Object.class);
            System.out.printf("Parsed json is of type %s\n\n", parsedJson.getClass().toString());
            if (parsedJson instanceof com.google.gson.internal.LinkedTreeMap) {
                com.google.gson.internal.LinkedTreeMap treeJson = (com.google.gson.internal.LinkedTreeMap) parsedJson;
                if (treeJson.containsKey("id")) {
                    String s = (String) treeJson.getOrDefault("id", "no key provided");
                    System.out.printf("\n\ntree contained id %s\n", s);
                } else {
                    System.out.printf("\n\ntree does not contain key id\n");
                }
            }
        } catch (IOException ex) {
            System.out.print(ex);
        } finally {
            response.close();
        }
    } catch (IOException ex) {
        System.out.print(ex);
    } finally {
        //lots of exceptions, just the connection and exit
        try {
            httpclient.close();
        } catch (IOException | NoSuchMethodError ex) {
            System.out.print(ex);
            return;
        }
    }
}

From source file:org.openeclass.EclassMobile.java

public static void main(String[] args) {

    try {//from  w  w  w .j  a  v  a 2 s . c om
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost("https://myeclass/modules/mobile/mlogin.php");
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair("uname", mUsername));
        nvps.add(new BasicNameValuePair("pass", mPassword));
        httppost.setEntity(new UrlEncodedFormEntity(nvps));

        System.out.println("twra tha kanei add");
        System.out.println("prin to response");

        HttpResponse response = httpclient.execute(httppost);
        StatusLine status = response.getStatusLine();

        if (status.getStatusCode() != 200)
            System.out.println("Invalid response from server: " + status.toString());

        System.out.println("meta to response");

        Header[] head = response.getAllHeaders();

        for (int i = 0; i < head.length; i++)
            System.out.println("to head exei " + head[i]);

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

        HttpEntity entity = response.getEntity();
        InputStream ips = entity.getContent();
        BufferedReader buf = new BufferedReader(new InputStreamReader(ips, "UTF-8"), 1024);

        StringBuilder sb = new StringBuilder();
        String s = "";

        while ((s = buf.readLine()) != null) {
            sb.append(s);
        }
        System.out.println("to sb einai " + sb.toString());

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

From source file:sadl.run.moe.MoeTest2.java

public static void main(String[] args) throws ClientProtocolException, IOException {
    final String postUrl = "http://pc-kbpool-8.cs.upb.de:6543/gp/next_points/epi";// put in your url
    try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) { // Use this instead
        final HistoryData h = new HistoryData();
        final Configuration c = new Configuration();
        final PdttaParameters parameters = new PdttaParameters();
        for (final Parameter p : parameters.parameters) {
            c.config.put(p, p.getDefault());
        }//  w w w .j a  v a 2 s.  co m
        h.history.put(c, 0.5);
        final HttpPost post = new HttpPost(postUrl);
        final String s = parameters.toJsonString(20, h);
        // final String s = Files.readAllLines(Paths.get("testfile")).get(0);
        // final StringEntity postingString = new StringEntity(gson.toJson(p));// convert your pojo to json
        final StringEntity postingString = new StringEntity(s);// convert your pojo to json
        post.setEntity(postingString);
        System.out.println(EntityUtils.toString(post.getEntity(), "UTF-8"));
        post.setHeader("Content-type", "application/json");
        try (CloseableHttpResponse response = httpClient.execute(post)) {
            final String responseString = EntityUtils.toString(response.getEntity(), "UTF-8");
            System.out.println(responseString);
        }
    }
    // This is the right query
    // {"domain_info": {"dim": 2, "domain_bounds": [{"max": 1.0, "min": 0.0},{"max": 0.0, "min": -1.0}]}, "gp_historical_info": {"points_sampled":
    // [{"value_var": 0.01, "value": 0.1, "point": [0.0,0.0]}, {"value_var": 0.01, "value": 0.2, "point": [1.0,-1.0]}]}, "num_to_sample": 1}
}