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

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

Introduction

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

Prototype

public void setEntity(final HttpEntity entity) 

Source Link

Usage

From source file:com.http.QuickStart.java

public static void main(String[] args) throws Exception {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    try {// w  w w  . j a v a2  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:org.vuphone.vandyupon.test.ImagePostTester.java

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

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

        fis.close();

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

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

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

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

From source file:com.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 ww w .  j ava2  s . com*/

    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:com.oocl.euc.ita.test.QuickStart.java

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

        //           HttpPost?
        HttpPost httpPost = new HttpPost("http://localhost:8080/qb-webapp/login");
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair("username", "Neolarry"));
        nvps.add(new BasicNameValuePair("password", "123456789"));
        httpPost.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8"));
        CloseableHttpResponse response2 = httpclient.execute(httpPost);

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

        HttpGet httpGet = new HttpGet("http://localhost:8080/qb-webapp/api/trainer");
        System.out.println(httpGet.getURI());
        CloseableHttpResponse response1 = httpclient.execute(httpGet);
        // The underlying HTTP connection is still held by the response object
        // to allow the response content to be streamed directly from the network socket.
        // In order to ensure correct deallocation of system resources
        // the user MUST call CloseableHttpResponse#close() from a finally clause.
        // Please note that if response content is not fully consumed the underlying
        // connection cannot be safely re-used and will be shut down and discarded
        // by the connection manager.
        try {
            //                System.out.println("get: "+response1.getStatusLine());
            HttpEntity entity1 = response1.getEntity();
            // do something useful with the response body
            // and ensure it is fully consumed
            String responseString = "";

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

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

            EntityUtils.consume(entity1);
        } finally {
            response1.close();
        }

    } finally {
        httpclient.close();
    }
}

From source file:com.newproject.ApacheHttp.java

public static void main(String[] args) throws Exception {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    String jsonFilePath = "/Users/vikasmohandoss/Documents/Cloud/test.txt";
    String url = "http://www.sentiment140.com/api/bulkClassifyJson&appid=vm2446@columbia.edu";
    JSONParser jsonParser = new JSONParser();
    JSONObject jsonObject = new JSONObject();
    URL obj = new URL(url);
    HttpURLConnection con = (HttpURLConnection) obj.openConnection();
    try {//  w w w.j  a  va 2s. c  o  m
        FileReader fileReader = new FileReader(jsonFilePath);
        jsonObject = (JSONObject) jsonParser.parse(fileReader);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (ParseException e) {
        e.printStackTrace();
    }
    System.out.println(jsonObject.toString());
    /*try {
    /*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();
    }*/
    try {
        HttpPost request = new HttpPost("http://www.sentiment140.com/api/bulkClassifyJson");
        StringEntity params = new StringEntity(jsonObject.toString());
        request.addHeader("content-type", "application/json");
        request.setEntity(params);
        HttpResponse response = httpclient.execute(request);
        System.out.println(response.toString());
        String result = EntityUtils.toString(response.getEntity());
        System.out.println(result);
        try {
            File file = new File("/Users/vikasmohandoss/Documents/Cloud/sentiment.txt");
            // if file doesnt exists, then create it
            if (!file.exists()) {
                file.createNewFile();
            }
            FileWriter fw = new FileWriter(file.getAbsoluteFile());
            BufferedWriter bw = new BufferedWriter(fw);
            bw.write(result);
            bw.close();
            System.out.println("Done");
        } catch (IOException e) {
            e.printStackTrace();
        }
        // handle response here...
    } catch (Exception ex) {
        // handle exception here
    } finally {
        httpclient.close();
    }
}

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 ava2s. c  o 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.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 w  w .  j  ava  2 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:chat.parse.ChatParse.java

/**
 * @param args the command line arguments
 *//*from www  . j  av a  2 s .  c  o  m*/
public static void main(String[] args) throws JSONException, IOException {

    String url = "https://api.parse.com/1/classes/";
    String applicationkey = "RfIUZYQki1tKxFhciTxjD4a712gy1SeY9sw7hhbO";
    String RestApiKey = "WjlZA2VIuonVgd6FKac6tpO8LGztARUHUKFEmeTi";

    CloseableHttpClient client = HttpClients.createDefault();
    HttpPost post = new HttpPost(url + "contatti");

    post.addHeader("Content-Type", "application/json");
    post.addHeader("X-Parse-Application-Id", applicationkey);
    post.addHeader("X-Parse-REST-API-Key", RestApiKey);

    JSONObject obj = new JSONObject();
    obj.put("nome", "Paolo");
    obj.put("surname", "Possanzini");
    obj.put("email", "paolo@teamdev.it");

    post.setEntity(new StringEntity(obj.toString()));

    client.execute(post);

}

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());
        }//from  w w w  . jav a 2 s .c om
        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}
}

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 {//from www  .  java  2 s.c  o  m
        HttpResponse resp = c.execute(post);
        resp.getEntity().writeTo(System.out);
    } catch (IOException e) {
        e.printStackTrace();
    }

}