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.javaquery.aws.elasticsearch.AddUpdateExample.java

public static void main(String[] args) throws UnsupportedEncodingException {
    /**//from  w w w  .j  ava 2  s  .com
     * 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: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);
    HttpClient httpclient = new DefaultHttpClient();

    // Execute the request
    HttpResponse response = null;//from   w w w  . j  av  a2 s . c om
    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.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);
    HttpClient httpclient = new DefaultHttpClient();

    // Execute the request
    HttpResponse response = null;/*from ww w .  j a  v  a 2 s.c om*/
    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:org.corfudb.sharedlog.examples.ConfigClnt.java

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

    DefaultHttpClient httpclient = new DefaultHttpClient();
    final BufferedReader prompt = new BufferedReader(new InputStreamReader(System.in));

    CorfuConfiguration C = null;/*ww  w  . j av a2 s.c om*/

    while (true) {

        System.out.print("> ");
        String line = prompt.readLine();
        if (line.startsWith("get")) {

            HttpGet httpget = new HttpGet("http://localhost:8000/corfu");

            System.out.println("Executing request: " + httpget.getRequestLine());
            HttpResponse response = (HttpResponse) httpclient.execute(httpget);

            System.out.println("----------------------------------------");
            System.out.println(response.getStatusLine());
            // response.getEntity().writeTo(System.out);
            // System.out.println();
            // System.out.println("----------------------------------------");

            C = new CorfuConfiguration(response.getEntity().getContent());
        } else {

            if (C == null) {
                System.out.println("configuration not set yet!");
                continue;
            }

            HttpPost httppost = new HttpPost("http://localhost:8000/corfu");
            httppost.setEntity(new StringEntity(C.ConfToXMLString()));

            System.out.println("Executing request: " + httppost.getRequestLine());
            HttpResponse response = httpclient.execute(httppost);

            System.out.println("----------------------------------------");
            System.out.println(response.getStatusLine());
            response.getEntity().writeTo(System.out);

        }
    }
    // httpclient.close();
}

From source file:com.mycompany.horus.Teste.java

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

    ServiceListener list = new ServiceListener();
    list.getHorusServicesList();/*from  w w w  . j a va 2s  .  c o  m*/

    String soapBody = "<soap:Envelope xmlns:soap=\"http://www.w3.org/2003/05/soap-envelope\" xmlns:est=\"http://servicos.saude.gov.br/horus/v1r0/EstoqueService\">\n"
            + " <soap:Header>\n"
            + " <wsse:Security xmlns:wsse=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wsswssecurity-secext-1.0.xsd\">\n"
            + " <wsse:UsernameToken wsu:Id=\"Id-0001334008436683-000000002c4a1908-1\" xmlns:wsu=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd\">\n"
            + " <wsse:Username>HORUS</wsse:Username>\n"
            + " <wsse:Password Type=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wssusername-token-profile-1.0#PasswordText\">SENHA</wsse:Password>\n"
            + " </wsse:UsernameToken>\n" + " </wsse:Security>\n" + " </soap:Header>\n"
            + " <soap:Body><est:requestConsultarPosicaoEstoquePorCNES>\n" + " <est:cnes>7604041</est:cnes>\n"
            + " </est:requestConsultarPosicaoEstoquePorCNES>\n" + " </soap:Body>\n" + "</soap:Envelope>\n";
    try {
        // Get target URL

        CloseableHttpClient httpclient = HttpClientBuilder.create().build();
        StringEntity strEntity = new StringEntity(soapBody, "UTF-8");
        strEntity.setContentType("text/xml");
        HttpPost post = new HttpPost("https://servicos.saude.gov.br/horus/v1r0/EstoqueService");
        post.setEntity(strEntity);

        // Execute request
        HttpResponse response = httpclient.execute(post);
        HttpEntity respEntity = response.getEntity();
        String resp = EntityUtils.toString(respEntity);
        if (respEntity != null) {
            System.out.println("Response:");
            System.out.println(resp);
            //Changing response to Xml file
            stringToDom(resp);

        } else {
            System.out.println("No Response");
        }
    } catch (Exception e) {
        System.out.println("Other exception = " + e.toString());
    }
}

From source file:ClientWithResponseHandlerPost.java

public final static void main(String[] args) throws Exception {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    try {//w w  w  .  j  a  v  a 2s  .c o  m
        List<NameValuePair> formparams = new ArrayList<NameValuePair>();
        formparams.add(new BasicNameValuePair("id", "KYacxNZ6QQc"));
        formparams.add(new BasicNameValuePair("calid", "adamm"));
        formparams.add(new BasicNameValuePair("content-out", "text/xml"));
        UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, Consts.UTF_8);

        //entity.setChunked(true);
        HttpPost httppost = new HttpPost("http://localhost:8080/export.wcap");
        httppost.setEntity(entity);

        System.out.println("executing request " + httppost.getURI());
        System.out.println("executing request " + httppost.getConfig());

        // Create a custom response handler
        ResponseHandler<String> responseHandler = new ResponseHandler<String>() {

            public String handleResponse(final HttpResponse response)
                    throws ClientProtocolException, IOException {
                int status = response.getStatusLine().getStatusCode();
                if (status >= 200 && status < 600) {
                    HttpEntity entity = response.getEntity();
                    return entity != null ? EntityUtils.toString(entity) : null;
                } else {
                    throw new ClientProtocolException("Unexpected response status: " + status);
                }
            }

        };
        String responseBody = httpclient.execute(httppost, responseHandler);
        System.out.println("----------------------------------------");
        System.out.println(responseBody);
        System.out.println("----------------------------------------");

    } finally {
        httpclient.close();
    }
}

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

public static void main(String[] args) throws UnsupportedEncodingException {
    /**/*from w w w  .  java2  s .  co  m*/
     * Amazon ElasticSearch Service URL:
     * endpoint + / + {index_name} + / + _bulk
     */
    String elastic_search_url = "http://xxxxx-yyyyy-r6nvlhpscgdwms5.ap-northeast-1.es.amazonaws.com/inventory/_bulk";

    /**
     * Records to add in elastic search
     * Important Note: For elastic search bulk add and update, it should be in following format.
     * 
     * {header} + {new_line} // Header for next line json document
     * {jsonDocument} + {new_line}
     * {header} + {new_line}
     * {jsonDocument} + {new_line}
     * 
     * New line at the end of String is compulsory.
     */
    String header_one = "{\"index\":{\"_index\":\"inventory\",\"_type\":\"simple\",\"_id\":\"123\"}}\n";
    String jsonDocument_one = "{\"id\": \"123\", \"name\": \"Apple iPhone 6s\", \"stock\" : 10}\n";
    String header_two = "{\"index\":{\"_index\":\"inventory\",\"_type\":\"simple\",\"_id\":\"456\"}}\n";
    String jsonDocument_two = "{\"id\": \"456\", \"name\": \"Apple iPhone 5s\", \"stock\" : 15}\n";

    String jsonDocumentBulk = header_one + jsonDocument_one + header_two + jsonDocument_two;

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

    /* 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:zz.pseas.ghost.login.weibo.WeibocnLogin.java

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

    // ?URL//from   w w w  .ja v a2s.  co  m
    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:myexamples.MyExamples.java

public static void main(String[] args) throws Exception {
    String tweetString = "";
    RefEntity refEntity = new RefEntity();
    String refEntityString = gson.toJson(refEntity);
    httpclient = HttpClients.createDefault();
    try {/*from  w w  w  . j  av  a2s.  c om*/
        //getExample();    
        tweetString = getTweet();
        StringEntity stringEntity = new StringEntity(refEntityString);
        HttpPost httppost = new HttpPost("http://localhost:9200/referenzer/reference");
        httppost.setEntity(stringEntity);
        CloseableHttpResponse response1 = httpclient.execute(httppost);
        System.out.println("responseStatus=" + response1.getStatusLine());
        PostResponseEntity pRE = gson.fromJson(EntityUtils.toString(response1.getEntity()),
                PostResponseEntity.class);
        System.out.println(pRE.toString(1));
        //System.out.println("response="+EntityUtils.toString(response1.getEntity()));
    } finally {
        httpclient.close();
    }

    System.out.println(tweetString);

    Gson gson = new Gson();
    TweetResponse tweetResponse = gson.fromJson(tweetString, TweetResponse.class);
    System.out.println(tweetResponse.toString(1));

    System.out.println(refEntityString);
}

From source file:es.tsb.ltba.nomhad.example.ClientWithResponseHandler.java

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

    DefaultHttpClient httpclient = new DefaultHttpClient();
    httpclient = wrapClient(httpclient);
    httpclient.getCredentialsProvider().setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),
            new UsernamePasswordCredentials("A100", "123456"));

    try {/*from   w  w  w. j  a v a 2s.  c  o m*/
        HttpGet httpget = new HttpGet(NOMHAD_URL_HEADER + "A100" + OBSERVATIONS_REQUEST);

        HttpPost httppost = new HttpPost(NOMHAD_URL_HEADER + "A100" + OBSERVATIONS_REQUEST);
        httppost.setEntity(new StringEntity(BODY_TEST));
        System.out.println("executing request " + httpget.getURI());

        // Create a response handler
        ResponseHandler<String> responseHandler = new BasicResponseHandler();
        String responseBody = httpclient.execute(httppost, responseHandler);
        System.out.println("----------------------------------------");
        System.out.println(responseBody);
        System.out.println("----------------------------------------");

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