Example usage for org.apache.http.message BasicHttpEntityEnclosingRequest setEntity

List of usage examples for org.apache.http.message BasicHttpEntityEnclosingRequest setEntity

Introduction

In this page you can find the example usage for org.apache.http.message BasicHttpEntityEnclosingRequest setEntity.

Prototype

public void setEntity(HttpEntity httpEntity) 

Source Link

Usage

From source file:com.ebay.spine.Launcher.java

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

    // not using the default parsing for the hub. Creating a simple one from the default.
    GridHubConfiguration config = new GridHubConfiguration();

    // adding the VNC capable servlet.
    List<String> servlets = new ArrayList<String>();
    servlets.add("web.ConsoleVNC");
    config.setServlets(servlets);/*  www . j  ava2 s.  c o m*/

    // capabilities are dynamic for VMs.
    config.setThrowOnCapabilityNotPresent(false);

    // forcing the host from command line param as the hub gets confused by all the VMWare network interfaces.
    for (int i = 0; i < args.length; i++) {
        if (args[i].startsWith("hubhost=")) {
            config.setHost(args[i].replace("hubhost=", ""));
        }
    }

    Hub h = new Hub(config);
    h.start();

    // and the nodes.

    // load the node templates.
    Map<String, JSONObject> templatesByNameMap = getTemplates("eugrid.json");

    // get the template to use for each VM
    Map<String, String> vmsMapping = getVMtoTemplateMapping("nodes.properties");

    // register each node using its template.
    for (String id : vmsMapping.keySet()) {
        String templateName = vmsMapping.get(id);
        JSONObject request = templatesByNameMap.get(templateName);
        request.getJSONObject("configuration").put("vm", id);

        BasicHttpEntityEnclosingRequest r = new BasicHttpEntityEnclosingRequest("POST",
                "http://" + hub + "/grid/register/");
        r.setEntity(new StringEntity(request.toString()));
        DefaultHttpClient client = new DefaultHttpClient();
        URL hubURL = new URL("http://" + hub);
        HttpHost host = new HttpHost(hubURL.getHost(), hubURL.getPort());
        HttpResponse response = client.execute(host, r);
    }

}

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 av a2s .c o m

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

From source file:io.aos.protocol.http.httpcommon.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, "Test/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 www  .ja v a 2  s . com

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

From source file:com.weibo.wesync.client.NHttpClient2.java

public static void main(String[] args) throws Exception {
    RSAPublicKey publicKey = RSAEncrypt.loadPublicKey("D:\\weibo\\meyou_gw\\conf\\public.pem");
    //  /* www .j av  a2s  .c o m*/
    byte[] cipher = RSAEncrypt.encrypt(publicKey, password.getBytes());
    password = RSAEncrypt.toHexString(cipher);

    // HTTP parameters for the client
    HttpParams params = new SyncBasicHttpParams();
    params.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 30000)
            .setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 30000)
            .setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 8 * 1024)
            .setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true);

    // Create HTTP protocol processing chain
    HttpProcessor httpproc = new ImmutableHttpProcessor(new HttpRequestInterceptor[] {
            // Use standard client-side protocol interceptors
            new RequestContent(), new RequestTargetHost(), new RequestConnControl(), new RequestUserAgent(),
            new RequestExpectContinue() });
    // Create client-side HTTP protocol handler
    HttpAsyncRequestExecutor protocolHandler = new HttpAsyncRequestExecutor();
    // Create client-side I/O event dispatch
    final IOEventDispatch ioEventDispatch = new DefaultHttpClientIODispatch(protocolHandler, params);
    // Create client-side I/O reactor
    IOReactorConfig config = new IOReactorConfig();
    config.setIoThreadCount(1);
    final ConnectingIOReactor ioReactor = new DefaultConnectingIOReactor(config);
    // Create HTTP connection pool
    BasicNIOConnPool pool = new BasicNIOConnPool(ioReactor, params);
    // Limit total number of connections to just two
    pool.setDefaultMaxPerRoute(2);
    pool.setMaxTotal(1);

    // Run the I/O reactor in a separate thread
    Thread t = new Thread(new Runnable() {

        public void run() {
            try {
                // Ready to go!
                ioReactor.execute(ioEventDispatch);
            } catch (InterruptedIOException ex) {
                System.err.println("Interrupted");
            } catch (IOException e) {
                System.err.println("I/O error: " + e.getMessage());
            }
            System.out.println("Shutdown");
        }

    });
    // Start the client thread
    t.start();
    // Create HTTP requester
    //        HttpAsyncRequester requester = new HttpAsyncRequester(
    //                httpproc, new DefaultConnectionReuseStrategy(), params);
    // Execute HTTP GETs to the following hosts and
    HttpHost[] targets = new HttpHost[] {
            //              new HttpHost("123.125.106.28", 8093, "http"),
            //              new HttpHost("123.125.106.28", 8093, "http"),
            //                new HttpHost("123.125.106.28", 8093, "http"),
            //                new HttpHost("123.125.106.28", 8093, "http"),
            //                new HttpHost("123.125.106.28", 8093, "http"),
            //                new HttpHost("123.125.106.28", 8093, "http"),
            //                new HttpHost("123.125.106.28", 8093, "http"),
            //                new HttpHost("123.125.106.28", 8093, "http"),
            //                new HttpHost("123.125.106.28", 8093, "http"),
            //                new HttpHost("123.125.106.28", 8093, "http"),
            //                new HttpHost("123.125.106.28", 8093, "http"),
            new HttpHost("123.125.106.28", 8082, "http") };

    final CountDownLatch latch = new CountDownLatch(targets.length);
    int callbackId = 0;

    for (int i = 0; i < 1; i++) {
        for (final HttpHost target : targets) {
            BasicHttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest("POST", "/wesync");

            //              String usrpwd = Base64.encodeBase64String((username + ":" + password).getBytes());
            //              request.setHeader("authorization", "Basic " + usrpwd);
            request.setHeader("uid", "2565640713");
            Meyou.MeyouPacket packet = null;

            if (callbackId == 0) {
                packet = Meyou.MeyouPacket.newBuilder().setCallbackId(String.valueOf(callbackId++))
                        .setSort(MeyouSort.notice).build();
            } else {
                packet = Meyou.MeyouPacket.newBuilder().setCallbackId(String.valueOf(callbackId++))
                        .setSort(MeyouSort.wesync).build();
            }

            ByteArrayEntity entity = new ByteArrayEntity(packet.toByteArray());
            request.setEntity(entity);
            //           BasicHttpRequest request = new BasicHttpRequest("GET", "/test.html");

            System.out.println("send ...");
            HttpAsyncRequester requester = new HttpAsyncRequester(httpproc,
                    new DefaultConnectionReuseStrategy(), params);
            requester.execute(new BasicAsyncRequestProducer(target, request), new BasicAsyncResponseConsumer(),
                    pool, new BasicHttpContext(),
                    // Handle HTTP response from a callback
                    new FutureCallback<HttpResponse>() {
                        public void completed(final HttpResponse response) {
                            StatusLine status = response.getStatusLine();
                            int code = status.getStatusCode();

                            if (code == 200) {
                                try {
                                    latch.countDown();
                                    DataInputStream in;
                                    in = new DataInputStream(response.getEntity().getContent());
                                    int packetLength = in.readInt();
                                    int start = 0;

                                    while (packetLength > 0) {
                                        ByteArrayOutputStream outstream = new ByteArrayOutputStream(
                                                packetLength);
                                        byte[] buffer = new byte[1024];
                                        int len = 0;

                                        while (start < packetLength
                                                && (len = in.read(buffer, start, packetLength)) > 0) {
                                            outstream.write(buffer, 0, len);
                                            start += len;
                                        }

                                        Meyou.MeyouPacket packet0 = Meyou.MeyouPacket
                                                .parseFrom(outstream.toByteArray());
                                        System.out.println(target + "->" + packet0);

                                        if ((len = in.read(buffer, start, 4)) > 0) {
                                            packetLength = Util.readPacketLength(buffer);
                                        } else {
                                            break;
                                        }
                                    }
                                } catch (IllegalStateException e) {
                                    // TODO Auto-generated catch block
                                    e.printStackTrace();
                                } catch (IOException e) {
                                    // TODO Auto-generated catch block
                                    e.printStackTrace();
                                }
                            } else {
                                System.out.println("error code=" + code + "|" + status.getReasonPhrase());
                            }
                        }

                        public void failed(final Exception ex) {
                            latch.countDown();
                            System.out.println(target + "->" + ex);
                        }

                        public void cancelled() {
                            latch.countDown();
                            System.out.println(target + " cancelled");
                        }

                    });

            Thread.sleep((long) (Math.random() * 10000));
        }
    }
    //        latch.await();
    //        System.out.println("Shutting down I/O reactor");
    //        ioReactor.shutdown();
    //        System.out.println("Done");
}

From source file:io.selendroid.server.util.HttpClientUtil.java

public static HttpResponse executeRequestWithPayload(String uri, int port, HttpMethod method, String payload)
        throws Exception {
    BasicHttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest(method.getName(), uri);
    request.setEntity(new StringEntity(payload, "UTF-8"));

    return getHttpClient().execute(new HttpHost("localhost", port), request);
}

From source file:io.selendroid.standalone.server.util.HttpClientUtil.java

public static HttpResponse executeRequestWithPayload(String uri, int port, HttpMethod method, String payload)
        throws Exception {
    BasicHttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest(method.name(), uri);
    request.setEntity(new StringEntity(payload, "UTF-8"));

    return getHttpClient().execute(new HttpHost("localhost", port), request);
}

From source file:de.tor.tribes.util.OBSTReportSender.java

public static void sendReport(URL pTarget, String pData) 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(pTarget.getHost(), pTarget.getPort());

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

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

    try {//  w  ww  .  j a  va2 s  .  co  m
        HttpEntity[] requestBodies = { new StringEntity(pData) };

        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",
                    pTarget.getPath() + "?" + pTarget.getQuery());

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

From source file:com.microsoft.services.sharepoint.http.FroyoHttpConnection.java

/**
 * Creates a request that can be accepted by the AndroidHttpClient
 * /*  ww w  .  jav  a  2 s.co  m*/
 * @param request
 *            The request information
 */
private static BasicHttpEntityEnclosingRequest createRealRequest(Request request) {
    BasicHttpEntityEnclosingRequest realRequest = new BasicHttpEntityEnclosingRequest(request.getVerb(),
            request.getUrl());

    if (request.getContent() != null) {
        realRequest.setEntity(new ByteArrayEntity(request.getContent()));
    }

    Map<String, String> headers = request.getHeaders();

    for (String key : headers.keySet()) {
        realRequest.addHeader(key, headers.get(key));
    }

    return realRequest;
}

From source file:com.microsoft.office365.http.FroyoHttpConnection.java

/**
 * Creates a request that can be accepted by the AndroidHttpClient
 * //from w  w w  .  ja  va2s .  c om
 * @param request
 *            The request information
 * @throws UnsupportedEncodingException
 */
private static BasicHttpEntityEnclosingRequest createRealRequest(Request request)
        throws UnsupportedEncodingException {
    BasicHttpEntityEnclosingRequest realRequest = new BasicHttpEntityEnclosingRequest(request.getVerb(),
            request.getUrl());

    if (request.getContent() != null) {
        realRequest.setEntity(new ByteArrayEntity(request.getContent()));
    }

    Map<String, String> headers = request.getHeaders();

    for (String key : headers.keySet()) {
        realRequest.addHeader(key, headers.get(key));
    }

    return realRequest;
}

From source file:microsoft.aspnet.signalr.client.http.android.AndroidHttpConnection.java

/**
 * Creates a request that can be accepted by the AndroidHttpClient
 * //w  w w.jav  a 2s.  c o  m
 * @param request
 *            The request information
 * @throws java.io.UnsupportedEncodingException
 */
private static BasicHttpEntityEnclosingRequest createRealRequest(Request request)
        throws UnsupportedEncodingException {
    BasicHttpEntityEnclosingRequest realRequest = new BasicHttpEntityEnclosingRequest(request.getVerb(),
            request.getUrl());

    if (request.getContent() != null) {
        realRequest.setEntity(new StringEntity(request.getContent()));
    }

    Map<String, String> headers = request.getHeaders();

    for (String key : headers.keySet()) {
        realRequest.addHeader(key, headers.get(key));
    }

    return realRequest;
}