Example usage for org.apache.http.client HttpClient execute

List of usage examples for org.apache.http.client HttpClient execute

Introduction

In this page you can find the example usage for org.apache.http.client HttpClient execute.

Prototype

<T> T execute(HttpUriRequest request, ResponseHandler<? extends T> responseHandler)
        throws IOException, ClientProtocolException;

Source Link

Document

Executes HTTP request using the default context and processes the response using the given response handler.

Usage

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 {//  w  w  w. ja v a 2 s  . c  o  m
        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.mama100.android.member.http.ClientCustomContext.java

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

    HttpClient httpclient = new DefaultHttpClient();

    // Create a local instance of cookie store
    CookieStore cookieStore = new BasicCookieStore();

    // Create local HTTP context
    HttpContext localContext = new BasicHttpContext();
    // Bind custom cookie store to the local context
    localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);

    HttpGet httpget = new HttpGet("http://www.weibo.com/");

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

    // Pass local context as a parameter
    HttpResponse response = httpclient.execute(httpget, localContext);
    HttpEntity entity = response.getEntity();

    System.out.println("----------------------------------------");
    System.out.println(response.getStatusLine());
    if (entity != null) {
        System.out.println("Response content length: " + entity.getContentLength());
    }// w w  w . j a v  a  2s  .  c  o  m
    List<Cookie> cookies = cookieStore.getCookies();
    for (int i = 0; i < cookies.size(); i++) {
        System.out.println("Local cookie: " + cookies.get(i));
    }

    // Consume response content
    if (entity != null) {
        entity.consumeContent();
    }

    System.out.println("----------------------------------------");

    // 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:com.hilatest.httpclient.apacheexample.ClientCustomContext.java

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

    HttpClient httpclient = new DefaultHttpClient();

    // Create a local instance of cookie store
    CookieStore cookieStore = new BasicCookieStore();

    // Create local HTTP context
    HttpContext localContext = new BasicHttpContext();
    // Bind custom cookie store to the local context
    localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);

    HttpGet httpget = new HttpGet("http://www.google.com/");

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

    // Pass local context as a parameter
    HttpResponse response = httpclient.execute(httpget, localContext);
    HttpEntity entity = response.getEntity();

    System.out.println("----------------------------------------");
    System.out.println(response.getStatusLine());
    if (entity != null) {
        System.out.println("Response content length: " + entity.getContentLength());
    }//from   w  w w . j a  v a  2  s.co  m
    List<Cookie> cookies = cookieStore.getCookies();
    for (int i = 0; i < cookies.size(); i++) {
        System.out.println("Local cookie: " + cookies.get(i));
    }

    // Consume response content
    if (entity != null) {
        entity.consumeContent();
    }

    System.out.println("----------------------------------------");

    // 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: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  .  ja  v a  2 s  . com*/

    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.mtea.macrotea_httpclient_study.ClientCustomContext.java

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

    HttpClient httpclient = new DefaultHttpClient();
    try {/*from   www  .java  2  s.  co m*/
        // CookieStore 
        CookieStore cookieStore = new BasicCookieStore();

        // HttpContext 
        HttpContext localContext = new BasicHttpContext();

        //HttpContextCookieStore
        localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);

        HttpGet httpget = new HttpGet("http://www.google.com/");

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

        // ?
        HttpResponse response = httpclient.execute(httpget, localContext);
        HttpEntity entity = response.getEntity();

        System.out.println("----------------------------------------");
        System.out.println(response.getStatusLine());
        if (entity != null) {
            System.out.println("Response content length: " + entity.getContentLength());
        }

        //???cookie
        List<Cookie> cookies = cookieStore.getCookies();
        for (int i = 0; i < cookies.size(); i++) {
            System.out.println("Local cookie: " + cookies.get(i));
        }

        //
        EntityUtils.consume(entity);

        System.out.println("----------------------------------------");

    } finally {
        //??httpclient???
        httpclient.getConnectionManager().shutdown();
    }
}

From source file:com.dlmu.heipacker.crawler.client.ClientCustomContext.java

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

    HttpClient httpclient = new DefaultHttpClient();
    try {/*  w  w w  . j av  a2  s  .  co m*/
        // Create a local instance of cookie store
        CookieStore cookieStore = new BasicCookieStore();

        // Create local HTTP context
        HttpContext localContext = new BasicHttpContext();
        // Bind custom cookie store to the local context
        localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);

        HttpGet httpget = new HttpGet("http://www.google.com/");

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

        // Pass local context as a parameter
        HttpResponse response = httpclient.execute(httpget, localContext);
        HttpEntity entity = response.getEntity();

        System.out.println("----------------------------------------");
        System.out.println(response.getStatusLine());
        if (entity != null) {
            System.out.println("Response content length: " + entity.getContentLength());
        }
        List<Cookie> cookies = cookieStore.getCookies();
        for (int i = 0; i < cookies.size(); i++) {
            System.out.println("Local cookie: " + cookies.get(i));
        }

        // Consume response content
        EntityUtils.consume(entity);

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

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  w  ww.j av  a  2s.  c om
    //.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.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);/* w ww . j a  v a  2s  .  co  m*/

    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.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.  java  2  s. com*/
    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);//w w w  .  jav a2 s. co 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));

}