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

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

Introduction

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

Prototype

public void setEntity(final HttpEntity entity) 

Source Link

Usage

From source file:com.puppetlabs.geppetto.forge.client.ForgeHttpClient.java

protected void assignJSONContent(HttpEntityEnclosingRequestBase request, Object params) {
    if (params != null) {
        request.addHeader(HttpHeaders.CONTENT_TYPE, CONTENT_TYPE_JSON + "; charset=" + UTF_8.name()); //$NON-NLS-1$
        byte[] data = toJson(params).getBytes(UTF_8);
        request.setEntity(new ByteArrayEntity(data));
    }/*from   www. ja  v a  2s  .c om*/
}

From source file:com.cloudant.mazha.HttpRequests.java

protected void setEntity(HttpEntityEnclosingRequestBase httpRequest, String json) {
    try {/*from   www  .j  a  v  a 2s  . c o m*/
        StringEntity entity = new StringEntity(json, "UTF-8");
        entity.setContentType("application/json");
        httpRequest.setEntity(entity);
    } catch (UnsupportedEncodingException e) {
        throw new IllegalArgumentException(e);
    }
}

From source file:com.comcast.csv.drivethru.api.HTTPRequestManager.java

/**
 * Sends request with data and returns {@link ResponseContainer} object containing response's status code and body.
 * @param client HttpClient use to send request
 * @param request Http request object to be sent out
 * @return {@link ResponseContainer} with response data
 * @throws IOException When there's an error sending out request
 */// www.  j  a  va 2 s  .  co m
private ResponseContainer sendRequestWithData(CloseableHttpClient client, HttpUriRequest request)
        throws IOException {
    HttpEntityEnclosingRequestBase httpMethod = (HttpEntityEnclosingRequestBase) request;
    HttpEntity entity = new ByteArrayEntity(mData);

    httpMethod.setEntity(entity);

    return sendRequest(client, httpMethod);
}

From source file:com.web.server.ProxyServlet.java

@Override
@SuppressWarnings("unchecked")
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    // Create new client to perform the proxied request
    HttpClient httpclient = new DefaultHttpClient();

    // Determine final URL
    StringBuffer uri = new StringBuffer();
    uri.append(targetServer);//w  w  w.  j  a  va 2 s  .co m
    uri.append(req.getRequestURI());

    // Add any supplied query strings
    String queryString = req.getQueryString();
    if (queryString != null) {
        uri.append("?" + queryString);
    }

    // Get HTTP method
    final String method = req.getMethod();
    // Create new HTTP request container
    HttpRequestBase request = null;

    // Get content length
    int contentLength = req.getContentLength();
    // Unknown content length ...
    //       if (contentLength == -1)
    //          throw new ServletException("Cannot handle unknown content length");
    // If we don't have an entity body, things are quite simple
    if (contentLength < 1) {
        request = new HttpRequestBase() {
            public String getMethod() {
                return method;
            }
        };
    } else {
        // Prepare request
        HttpEntityEnclosingRequestBase tmpRequest = new HttpEntityEnclosingRequestBase() {
            public String getMethod() {
                return method;
            }
        };

        // Transfer entity body from the received request to the new request
        InputStreamEntity entity = new InputStreamEntity(req.getInputStream(), contentLength);
        tmpRequest.setEntity(entity);

        request = tmpRequest;
    }

    // Set URI
    try {
        request.setURI(new URI(uri.toString()));
    } catch (URISyntaxException e) {
        throw new ServletException("URISyntaxException: " + e.getMessage());
    }

    // Copy headers from old request to new request
    // @todo not sure how this handles multiple headers with the same name
    Enumeration<String> headers = req.getHeaderNames();
    while (headers.hasMoreElements()) {
        String headerName = headers.nextElement();
        String headerValue = req.getHeader(headerName);
        // Skip Content-Length and Host
        String lowerHeader = headerName.toLowerCase();
        if (lowerHeader.equals("content-length") == false && lowerHeader.equals("host") == false) {
            //             System.out.println(headerName.toLowerCase() + ": " + headerValue);
            request.addHeader(headerName, headerValue);
        }
    }

    // Execute the request
    HttpResponse response = httpclient.execute(request);

    // Transfer status code to the response
    StatusLine status = response.getStatusLine();
    resp.setStatus(status.getStatusCode());
    // resp.setStatus(status.getStatusCode(), status.getReasonPhrase()); // This seems to be deprecated. Yes status message is "ambigous", but I don't approve

    // Transfer headers to the response
    Header[] responseHeaders = response.getAllHeaders();
    for (int i = 0; i < responseHeaders.length; i++) {
        Header header = responseHeaders[i];
        resp.addHeader(header.getName(), header.getValue());
    }

    // Transfer proxy response entity to the servlet response
    HttpEntity entity = response.getEntity();
    InputStream input = entity.getContent();
    OutputStream output = resp.getOutputStream();
    int b = input.read();
    while (b != -1) {
        output.write(b);
        b = input.read();
    }

    // Clean up
    input.close();
    output.close();
    httpclient.getConnectionManager().shutdown();
}

From source file:com.cloudant.mazha.HttpRequests.java

protected void setEntity(HttpEntityEnclosingRequestBase httpRequest, String contentType, InputStream is,
        long contentLength) {
    InputStreamEntity entity = new InputStreamEntity(is, contentLength);
    entity.setContentType(contentType);//from w ww. j  a v a  2s  .  co  m
    httpRequest.setEntity(entity);
}

From source file:com.flipkart.poseidon.handlers.http.impl.HttpConnectionPool.java

/**
 *
 * @param request/*from w w w  .  jav  a2 s  .c  om*/
 * @param data
 */
private void setRequestBody(HttpEntityEnclosingRequestBase request, byte[] data) {
    if (data != null) {
        if (this.requestGzipEnabled) {
            request.addHeader(CONTENT_ENCODING, COMPRESSION_TYPE);
            request.setEntity(new GzipCompressingEntity(new ByteArrayEntity(data)));
        } else {
            request.setEntity(new ByteArrayEntity(data));
        }
    }
}

From source file:org.gnode.wda.server.ProxyServlet.java

License:asdf

@Override
@SuppressWarnings("unchecked")
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    // Create new client to perform the proxied request
    HttpClient httpclient = new DefaultHttpClient();

    // Determine final URL
    StringBuffer uri = new StringBuffer();
    uri.append(targetServer);//ww w  .j a  v  a 2 s.c  om
    // This is a very bad hack. In order to remove my proxy servlet-path, I have used a substring method.
    // Turns "/proxy/asdf" into "/asdf"
    uri.append(req.getRequestURI().substring(6));

    //    Add any supplied query strings
    String queryString = req.getQueryString();
    if (queryString != null) {
        uri.append("?" + queryString);
    }

    // Get HTTP method
    final String method = req.getMethod();
    // Create new HTTP request container
    HttpRequestBase request = null;

    // Get content length
    int contentLength = req.getContentLength();
    //    Unknown content length ...
    // if (contentLength == -1)
    // throw new ServletException("Cannot handle unknown content length");
    // If we don't have an entity body, things are quite simple
    if (contentLength < 1) {
        request = new HttpRequestBase() {
            public String getMethod() {
                return method;
            }
        };
    } else {
        // Prepare request
        HttpEntityEnclosingRequestBase tmpRequest = new HttpEntityEnclosingRequestBase() {
            public String getMethod() {
                return method;
            }
        };

        // Transfer entity body from the received request to the new request
        InputStreamEntity entity = new InputStreamEntity(req.getInputStream(), contentLength);
        tmpRequest.setEntity(entity);

        request = tmpRequest;
    }

    //    Set URI
    try {
        request.setURI(new URI(uri.toString()));
    } catch (URISyntaxException e) {
        throw new ServletException("URISyntaxException: " + e.getMessage());
    }

    //       Copy headers from old request to new request
    // @todo not sure how this handles multiple headers with the same name
    Enumeration<String> headers = req.getHeaderNames();
    while (headers.hasMoreElements()) {
        String headerName = headers.nextElement();
        String headerValue = req.getHeader(headerName);
        //       Skip Content-Length and Host
        String lowerHeader = headerName.toLowerCase();
        if (lowerHeader.equals("content-length") == false && lowerHeader.equals("host") == false) {
            //    System.out.println(headerName.toLowerCase() + ": " + headerValue);
            request.addHeader(headerName, headerValue);
        }
    }

    // Execute the request
    HttpResponse response = httpclient.execute(request);

    // Transfer status code to the response
    StatusLine status = response.getStatusLine();
    resp.setStatus(status.getStatusCode());
    // resp.setStatus(status.getStatusCode(), status.getReasonPhrase()); // This seems to be deprecated. Yes status message is "ambigous", but I don't approve

    // Transfer headers to the response
    Header[] responseHeaders = response.getAllHeaders();
    for (int i = 0; i < responseHeaders.length; i++) {
        Header header = responseHeaders[i];
        resp.addHeader(header.getName(), header.getValue());
    }

    //    Transfer proxy response entity to the servlet response
    HttpEntity entity = response.getEntity();

    if (entity == null)
        return;

    InputStream input = entity.getContent();
    OutputStream output = resp.getOutputStream();
    int b = input.read();
    while (b != -1) {
        output.write(b);
        b = input.read();
    }

    //       Clean up
    input.close();
    output.close();
    httpclient.getConnectionManager().shutdown();
}

From source file:com.hippoapp.asyncmvp.http.AsyncHttpClient.java

private HttpEntityEnclosingRequestBase addEntityToRequestBase(AsyncHttpRequestParams params) {
    HttpEntityEnclosingRequestBase requestBase = new HttpPost(params.getBaseUrl());
    if (params.mHttpParams.size() > 0) {
        requestBase.setEntity(params.getEntity());
    }//www . ja va  2s . com
    return requestBase;
}

From source file:com.socialize.api.DefaultSocializeRequestFactory.java

private void populatePutPost(SocializeSession session, HttpEntityEnclosingRequestBase request, String payload)
        throws SocializeException {
    try {//from w w  w .j  a v  a 2  s .co m
        List<NameValuePair> data = new ArrayList<NameValuePair>();
        data.add(new BasicNameValuePair("payload", payload));
        UrlEncodedFormEntity entity = new UrlEncodedFormEntity(data, "UTF-8");
        request.setEntity(entity);
        sign(session, request);
    } catch (UnsupportedEncodingException e) {
        throw new SocializeException(e);
    }
}

From source file:com.dp.bigdata.taurus.web.servlet.CreateTaskServlet.java

@Override
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    HttpClient httpclient = new DefaultHttpClient();
    // Determine final URL
    StringBuffer uri = new StringBuffer();

    if (req.getParameter("update") != null) {
        uri.append(targetUri).append("/").append(req.getParameter("update"));
    } else {/*  w  ww.j  a  v  a2 s.c o  m*/
        uri.append(targetUri);
    }
    LOG.info("Access URI : " + uri.toString());
    // Get HTTP method
    final String method = req.getMethod();
    // Create new HTTP request container
    HttpRequestBase request = null;

    // Get content length
    int contentLength = req.getContentLength();
    // Unknown content length ...
    // if (contentLength == -1)
    // throw new ServletException("Cannot handle unknown content length");
    // If we don't have an entity body, things are quite simple
    if (contentLength < 1) {
        request = new HttpRequestBase() {
            public String getMethod() {
                return method;
            }
        };
    } else {
        // Prepare request
        HttpEntityEnclosingRequestBase tmpRequest = new HttpEntityEnclosingRequestBase() {
            public String getMethod() {
                return method;
            }
        };
        // Transfer entity body from the received request to the new request
        InputStreamEntity entity = new InputStreamEntity(req.getInputStream(), contentLength);
        tmpRequest.setEntity(entity);
        request = tmpRequest;
    }

    // Set URI
    try {
        request.setURI(new URI(uri.toString()));
    } catch (URISyntaxException e) {
        throw new ServletException("URISyntaxException: " + e.getMessage());
    }

    // Copy headers from old request to new request
    // @todo not sure how this handles multiple headers with the same name
    Enumeration<?> headers = req.getHeaderNames();
    while (headers.hasMoreElements()) {
        String headerName = (String) headers.nextElement();
        String headerValue = req.getHeader(headerName);
        //LOG.info("header: " + headerName + " value: " + headerValue);
        // Skip Content-Length and Host
        String lowerHeader = headerName.toLowerCase();
        if (lowerHeader.equals("content-type")) {
            request.addHeader(headerName, headerValue + ";charset=\"utf-8\"");
        } else if (!lowerHeader.equals("content-length") && !lowerHeader.equals("host")) {
            request.addHeader(headerName, headerValue);
        }
    }

    // Execute the request
    HttpResponse response = httpclient.execute(request);
    // Transfer status code to the response
    StatusLine status = response.getStatusLine();
    resp.setStatus(status.getStatusCode());

    // Transfer headers to the response
    Header[] responseHeaders = response.getAllHeaders();
    for (int i = 0; i < responseHeaders.length; i++) {
        Header header = responseHeaders[i];
        if (!header.getName().equals("Transfer-Encoding"))
            resp.addHeader(header.getName(), header.getValue());
    }

    // Transfer proxy response entity to the servlet response
    HttpEntity entity = response.getEntity();
    InputStream input = entity.getContent();
    OutputStream output = resp.getOutputStream();

    byte buffer[] = new byte[50];
    while (input.read(buffer) != -1) {
        output.write(buffer);
    }
    //        int b = input.read();
    //        while (b != -1) {
    //            output.write(b);
    //            b = input.read();
    //        }
    // Clean up
    input.close();
    output.close();
    httpclient.getConnectionManager().shutdown();
}