Example usage for org.apache.http.entity StringEntity StringEntity

List of usage examples for org.apache.http.entity StringEntity StringEntity

Introduction

In this page you can find the example usage for org.apache.http.entity StringEntity StringEntity.

Prototype

public StringEntity(String str, Charset charset) 

Source Link

Usage

From source file:com.javaquery.apache.httpclient.HttpPutExample.java

public static void main(String[] args) {
    /* Create object of CloseableHttpClient */
    CloseableHttpClient httpClient = HttpClients.createDefault();

    /* Prepare put request */
    HttpPut httpPut = new HttpPut("http://www.example.com/api/customer");
    /* Add headers to get request */
    httpPut.addHeader("Authorization", "value");

    /* Prepare StringEntity from JSON */
    StringEntity jsonData = new StringEntity("{\"id\":\"123\", \"name\":\"Vicky Thakor\"}", "UTF-8");
    /* Body of request */
    httpPut.setEntity(jsonData);/*from  w ww  .j  a  v a 2  s.  c  om*/

    /* Response handler for after request execution */
    ResponseHandler<String> responseHandler = new ResponseHandler<String>() {

        @Override
        public String handleResponse(HttpResponse httpResponse) throws ClientProtocolException, IOException {
            /* Get status code */
            int httpResponseCode = httpResponse.getStatusLine().getStatusCode();
            System.out.println("Response code: " + httpResponseCode);
            if (httpResponseCode >= 200 && httpResponseCode < 300) {
                /* Convert response to String */
                HttpEntity entity = httpResponse.getEntity();
                return entity != null ? EntityUtils.toString(entity) : null;
            } else {
                return null;
                /* throw new ClientProtocolException("Unexpected response status: " + httpResponseCode); */
            }
        }
    };

    try {
        /* Execute URL and attach after execution response handler */
        String strResponse = httpClient.execute(httpPut, responseHandler);
        /* Print the response */
        System.out.println("Response: " + strResponse);
    } catch (IOException ex) {
        ex.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 ww w  .  jav a 2  s  .c  om
    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 w w .j  a v  a  2  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.javaquery.apache.httpclient.HttpPostExample.java

public static void main(String[] args) throws UnsupportedEncodingException {
    /* Create object of CloseableHttpClient */
    CloseableHttpClient httpClient = HttpClients.createDefault();

    /* Prepare POST request */
    HttpPost httpPost = new HttpPost("http://www.example.com/api/customer");
    /* Add headers to POST request */
    httpPost.addHeader("Authorization", "value");
    httpPost.addHeader("Content-Type", "application/json");

    /* Prepare StringEntity from JSON */
    StringEntity jsonData = new StringEntity("{\"id\":\"123\", \"name\":\"Vicky Thakor\"}", "UTF-8");
    /* Body of request */
    httpPost.setEntity(jsonData);//from w ww  .  ja  v  a  2  s. co m

    /* Response handler for after request execution */
    ResponseHandler<String> responseHandler = new ResponseHandler<String>() {

        @Override
        public String handleResponse(HttpResponse httpResponse) throws ClientProtocolException, IOException {
            /* Get status code */
            int httpResponseCode = httpResponse.getStatusLine().getStatusCode();
            System.out.println("Response code: " + httpResponseCode);
            if (httpResponseCode >= 200 && httpResponseCode < 300) {
                /* Convert response to String */
                HttpEntity entity = httpResponse.getEntity();
                return entity != null ? EntityUtils.toString(entity) : null;
            } else {
                return null;
                /* throw new ClientProtocolException("Unexpected response status: " + httpResponseCode); */
            }
        }
    };

    try {
        /* Execute URL and attach after execution response handler */
        String strResponse = httpClient.execute(httpPost, responseHandler);
        /* Print the response */
        System.out.println("Response: " + strResponse);
    } catch (IOException ex) {
        ex.printStackTrace();
    }
}

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

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

    ServiceListener list = new ServiceListener();
    list.getHorusServicesList();/*w w  w.  j a v a2  s .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: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  www.ja  va2 s  .  c o m
    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:com.cloudhopper.sxmp.PostMO.java

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

    String URL = "https://sms.twitter.com/receive/cloudhopper";
    String text = "HELP";
    String srcAddr = "+16504304922";

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

    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("  <operatorId>" + operatorId + "</operatorId>\n")
            .append("  <sourceAddress type=\"international\">" + srcAddr + "</sourceAddress>\n")
            .append("  <destinationAddress type=\"network\">40404</destinationAddress>\n")
            .append("  <text encoding=\"ISO-8859-1\">" + HexUtil.toHexString(text.getBytes()) + "</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 {//from ww  w .  jav  a 2 s  . com
        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: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";
    }/*  ww  w  .j  ava  2s.co  m*/

    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:com.cloudhopper.sxmp.Post.java

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

    String message = "Test With @ Character";
    //String message = "Tell Twitter what you're doing!\nStd msg charges apply. Send 'stop' to quit.\nVisit twitter.com or email help@twitter.com for help.";

    StringBuilder string0 = new StringBuilder(200).append("<?xml version=\"1.0\"?>\n")
            .append("<operation type=\"submit\">\n")
            .append(" <account username=\"customer1\" password=\"password1\"/>\n")
            .append(" <submitRequest referenceId=\"MYREF102020022\">\n")
            .append("  <operatorId>75</operatorId>\n").append("  <deliveryReport>true</deliveryReport>\n")
            .append("  <sourceAddress type=\"network\">40404</sourceAddress>\n")
            .append("  <destinationAddress type=\"international\">+13135551234</destinationAddress>\n")
            .append("  <text encoding=\"ISO-8859-1\">" + HexUtil.toHexString(message.getBytes("ISO-8859-1"))
                    + "</text>\n")
            .append(" </submitRequest>\n").append("</operation>\n").append("");

    /**//from ww w  .j  av a 2s  .c  o m
    //.append("<!DOCTYPE chapter PUBLIC \"-//OASIS//DTD DocBook XML//EN\" \"../dtds/docbookx.dtd\">")
    //.append("<!DOCTYPE chapter PUBLIC \"-//OASIS//DTD DocBook XML//EN\">")
    .append("<submitRequest sequenceId=\"1000\">\n")
    .append("   <!-- this is a comment -->\n")
    .append("   <account username=\"testaccount\" password=\"testpassword\"/>\n")
    .append("   <option />\n")
    .append("   <messageRequest referenceId=\"MYMESSREF\">\n")
    //.append("       <sourceAddress>+13135551212</sourceAddress>\n")
    .append("       <destinationAddress>+13135551200</destinationAddress>\n")
    .append("       <text><![CDATA[Hello World]]></text>\n")
    .append("   </messageRequest>\n")
    .append("</submitRequest>")
    .append("");
     */

    // Get target URL
    String strURL = "http://localhost:9080/api/sxmp/1.0";

    // Get file to be posted
    //String strXMLFilename = args[1];
    //File input = new File(strXMLFilename);

    HttpClient client = new DefaultHttpClient();

    long totalStart = System.currentTimeMillis();

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

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

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

}

From source file:com.sourcecode.youku.ElementalHttpPost.java

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

    HttpParams params = new SyncBasicHttpParams();
    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setContentCharset(params, "UTF-8");
    HttpProtocolParams.setUserAgent(params, "HttpComponents/1.1");
    HttpProtocolParams.setUseExpectContinue(params, true);

    HttpProcessor httpproc = new ImmutableHttpProcessor(new HttpRequestInterceptor[] {
            // Required protocol interceptors
            new RequestContent(), new RequestTargetHost(),
            // Recommended protocol interceptors
            new RequestConnControl(), new RequestUserAgent(), new RequestExpectContinue() });

    HttpRequestExecutor httpexecutor = new HttpRequestExecutor();

    HttpContext context = new BasicHttpContext(null);

    HttpHost host = new HttpHost("localhost", 8080);

    DefaultHttpClientConnection conn = new DefaultHttpClientConnection();
    ConnectionReuseStrategy connStrategy = new DefaultConnectionReuseStrategy();

    context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn);
    context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, host);

    try {/*from w  ww  .j a  va  2  s. c om*/

        HttpEntity[] requestBodies = { new StringEntity("This is the first test request", "UTF-8"),
                new ByteArrayEntity("This is the second test request".getBytes("UTF-8")),
                new InputStreamEntity(new ByteArrayInputStream(
                        "This is the third test request (will be chunked)".getBytes("UTF-8")), -1) };

        for (int i = 0; i < requestBodies.length; i++) {
            if (!conn.isOpen()) {
                Socket socket = new Socket(host.getHostName(), host.getPort());
                conn.bind(socket, params);
            }
            BasicHttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest("POST",
                    "/servlets-examples/servlet/RequestInfoExample");
            request.setEntity(requestBodies[i]);
            System.out.println(">> Request URI: " + request.getRequestLine().getUri());

            request.setParams(params);
            httpexecutor.preProcess(request, httpproc, context);
            HttpResponse response = httpexecutor.execute(request, conn, context);
            response.setParams(params);
            httpexecutor.postProcess(response, httpproc, context);

            System.out.println("<< Response: " + response.getStatusLine());
            System.out.println(EntityUtils.toString(response.getEntity()));
            System.out.println("==============");
            if (!connStrategy.keepAlive(response, context)) {
                conn.close();
            } else {
                System.out.println("Connection kept alive...");
            }
        }
    } finally {
        conn.close();
    }
}