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:net.community.chest.gitcloud.facade.frontend.git.GitController.java

private CloseableHttpResponse transferPostedData(HttpEntityEnclosingRequestBase postRequest,
        final HttpServletRequest req) throws IOException {
    InputStream postData = req.getInputStream();
    try {/*w ww.  j ava  2s.co  m*/
        if (logger.isTraceEnabled()) {
            LineLevelAppender appender = new LineLevelAppender() {
                @Override
                @SuppressWarnings("synthetic-access")
                public void writeLineData(CharSequence lineData) throws IOException {
                    logger.trace("transferPostedData(" + req.getMethod() + ")[" + req.getRequestURI() + "]["
                            + req.getQueryString() + "] C: " + lineData);
                }

                @Override
                public boolean isWriteEnabled() {
                    return true;
                }
            };
            postData = new TeeInputStream(postData, new HexDumpOutputStream(appender), true);
        }
        postRequest.setEntity(new InputStreamEntity(postData));
        return client.execute(postRequest);
    } finally {
        postData.close();
    }
}

From source file:org.doctester.testbrowser.TestBrowserImpl.java

private Response makePostOrPutRequest(Request httpRequest) {

    org.apache.http.HttpResponse apacheHttpClientResponse;
    Response response = null;//from  ww  w . j a  v  a  2 s  .c om

    try {

        httpClient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);

        HttpEntityEnclosingRequestBase apacheHttpRequest;

        if (POST.equalsIgnoreCase(httpRequest.httpRequestType)) {

            apacheHttpRequest = new HttpPost(httpRequest.uri);

        } else {

            apacheHttpRequest = new HttpPut(httpRequest.uri);
        }

        if (httpRequest.headers != null) {
            // add all headers
            for (Entry<String, String> header : httpRequest.headers.entrySet()) {
                apacheHttpRequest.addHeader(header.getKey(), header.getValue());
            }
        }

        ///////////////////////////////////////////////////////////////////
        // Either add form parameters...
        ///////////////////////////////////////////////////////////////////
        if (httpRequest.formParameters != null) {

            List<BasicNameValuePair> formparams = Lists.newArrayList();
            for (Entry<String, String> parameter : httpRequest.formParameters.entrySet()) {

                formparams.add(new BasicNameValuePair(parameter.getKey(), parameter.getValue()));
            }

            // encode form parameters and add
            UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams);
            apacheHttpRequest.setEntity(entity);

        }

        ///////////////////////////////////////////////////////////////////
        // Or add multipart file upload
        ///////////////////////////////////////////////////////////////////
        if (httpRequest.filesToUpload != null) {

            MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);

            for (Map.Entry<String, File> entry : httpRequest.filesToUpload.entrySet()) {

                // For File parameters
                entity.addPart(entry.getKey(), new FileBody((File) entry.getValue()));

            }

            apacheHttpRequest.setEntity(entity);

        }

        ///////////////////////////////////////////////////////////////////
        // Or add payload and convert if Json or Xml
        ///////////////////////////////////////////////////////////////////
        if (httpRequest.payload != null) {

            if (httpRequest.headers.containsKey(HEADER_CONTENT_TYPE)
                    && httpRequest.headers.containsValue(APPLICATION_JSON_WITH_CHARSET_UTF8)) {

                String string = new ObjectMapper().writeValueAsString(httpRequest.payload);

                StringEntity entity = new StringEntity(string, "utf-8");
                entity.setContentType("application/json; charset=utf-8");

                apacheHttpRequest.setEntity(entity);

            } else if (httpRequest.headers.containsKey(HEADER_CONTENT_TYPE)
                    && httpRequest.headers.containsValue(APPLICATION_XML_WITH_CHARSET_UTF_8)) {

                String string = new XmlMapper().writeValueAsString(httpRequest.payload);

                StringEntity entity = new StringEntity(string, "utf-8");
                entity.setContentType(APPLICATION_XML_WITH_CHARSET_UTF_8);

                apacheHttpRequest.setEntity(new StringEntity(string, "utf-8"));

            } else if (httpRequest.payload instanceof String) {

                StringEntity entity = new StringEntity((String) httpRequest.payload, "utf-8");
                apacheHttpRequest.setEntity(entity);

            } else {

                StringEntity entity = new StringEntity(httpRequest.payload.toString(), "utf-8");
                apacheHttpRequest.setEntity(entity);

            }

        }

        setHandleRedirect(apacheHttpRequest, httpRequest.followRedirects);

        // Here we go!
        apacheHttpClientResponse = httpClient.execute(apacheHttpRequest);
        response = convertFromApacheHttpResponseToDocTesterHttpResponse(apacheHttpClientResponse);

        apacheHttpRequest.releaseConnection();

    } catch (IOException e) {
        logger.error("Fatal problem creating POST or PUT request in TestBrowser", e);
        throw new RuntimeException(e);
    }

    return response;

}

From source file:com.android.volley.toolbox.http.HttpClientStack.java

private static void setEntityIfNonEmptyBody(HttpEntityEnclosingRequestBase httpRequest, Request<?> request)
        throws IOException, AuthFailureError {

    if (request.containsFile()) {
        /* MultipartEntity multipartEntity = new MultipartEntity();
        final Map<String, MultiPartParam> multipartParams = request.getMultiPartParams();
        for (String key : multipartParams.keySet()) {
        multipartEntity.addPart(new StringPart(key, multipartParams.get(key).value));
        }//from w ww . j  av  a2 s  .  c om
                
        final Map<String, File> filesToUpload = request.getFilesToUpload();
        if(filesToUpload!=null){
        for (String key : filesToUpload.keySet()) {
        File file = filesToUpload.get(key) ;
                
        if (file==null || !file.exists()) {
         throw new IOException(String.format("File not found: %s",file.getAbsolutePath()));
        }
                
        if (file.isDirectory()) {
         throw new IOException(String.format("File is a directory: %s", file.getAbsolutePath()));
        }
                
        multipartEntity.addPart(new FilePart(key, file, null, null));
        }
        }
        httpRequest.setEntity(multipartEntity);
        */
        MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
        final Map<String, MultiPartParam> multipartParams = request.getMultiPartParams();
        for (String key : multipartParams.keySet()) {
            multipartEntity.addPart(key,
                    new StringBody(multipartParams.get(key).value, "text/plain", Charset.forName("UTF-8")));
        }

        final Map<String, File> filesToUpload = request.getFilesToUpload();
        if (filesToUpload != null) {
            for (String key : filesToUpload.keySet()) {
                File file = filesToUpload.get(key);

                if (file == null || !file.exists()) {
                    throw new IOException(String.format("File not found: %s", file.getAbsolutePath()));
                }

                if (file.isDirectory()) {
                    throw new IOException(String.format("File is a directory: %s", file.getAbsolutePath()));
                }
                multipartEntity.addPart(key, new FileBody(file));
            }
        }
        httpRequest.setEntity(multipartEntity);

    } else {
        byte[] body = request.getBody();
        if (body != null) {
            HttpEntity entity = new ByteArrayEntity(body);
            httpRequest.setEntity(entity);
        }
    }
}

From source file:cn.com.loopj.android.http.AsyncHttpClient.java

/**
 * Perform a HTTP POST request and track the Android Context which initiated the request. Set
 * headers only for this request//from www .  ja va2s .co  m
 *
 * @param context         the Android Context which initiated the request.
 * @param url             the URL to send the request to.
 * @param headers         set headers only for this request
 * @param params          additional POST parameters to send with the request.
 * @param contentType     the content type of the payload you are sending, for example
 *                        application/json if sending a json payload.
 * @param responseHandler the response handler instance that should handle the response.
 * @return RequestHandle of future request process
 */
public RequestHandle post(Context context, String url, Header[] headers, RequestParams params,
        String contentType, ResponseHandlerInterface responseHandler) {
    HttpEntityEnclosingRequestBase request = new HttpPost(getURI(url));
    if (params != null)
        request.setEntity(paramsToEntity(params, responseHandler));
    if (headers != null)
        request.setHeaders(headers);
    return sendRequest(httpClient, httpContext, request, contentType, responseHandler, context);
}

From source file:com.evolveum.polygon.connector.drupal.DrupalConnector.java

protected JSONObject callRequest(HttpEntityEnclosingRequestBase request, JSONObject jo) throws IOException {
    // don't log request here - password field !!!
    LOG.ok("request URI: {0}", request.getURI());
    request.setHeader("Content-Type", CONTENT_TYPE);

    authHeader(request);/*from   w  ww  .j av  a2s. c o  m*/

    HttpEntity entity = new ByteArrayEntity(jo.toString().getBytes("UTF-8"));
    request.setEntity(entity);
    CloseableHttpResponse response = execute(request);
    LOG.ok("response: {0}", response);
    processDrupalResponseErrors(response);

    String result = EntityUtils.toString(response.getEntity());
    LOG.ok("response body: {0}", result);
    closeResponse(response);
    return new JSONObject(result);
}

From source file:cn.com.loopj.android.http.AsyncHttpClient.java

/**
 * Applicable only to HttpRequest methods extending HttpEntityEnclosingRequestBase, which is for
 * example not DELETE/*from  w w w . ja va 2 s .  c  o m*/
 *
 * @param entity      entity to be included within the request
 * @param requestBase HttpRequest instance, must not be null
 */
private HttpEntityEnclosingRequestBase addEntityToRequestBase(HttpEntityEnclosingRequestBase requestBase,
        HttpEntity entity) {
    if (entity != null) {
        requestBase.setEntity(entity);
    }

    return requestBase;
}

From source file:org.apache.camel.component.olingo2.api.impl.Olingo2AppImpl.java

private <T> void writeContent(final Edm edm, HttpEntityEnclosingRequestBase httpEntityRequest,
        final UriInfoWithType uriInfo, final Object content, final Olingo2ResponseHandler<T> responseHandler) {

    try {/*from  www  .ja  v a 2s .  c  o m*/
        // process resource by UriType
        final ODataResponse response = writeContent(edm, uriInfo, content);

        // copy all response headers
        for (String header : response.getHeaderNames()) {
            httpEntityRequest.setHeader(header, response.getHeader(header));
        }

        // get (http) entity which is for default Olingo2 implementation an InputStream
        if (response.getEntity() instanceof InputStream) {
            httpEntityRequest.setEntity(new InputStreamEntity((InputStream) response.getEntity()));
            /*
                            // avoid sending it without a header field set
                            if (!httpEntityRequest.containsHeader(HttpHeaders.CONTENT_TYPE)) {
            httpEntityRequest.addHeader(HttpHeaders.CONTENT_TYPE, getContentType());
                            }
            */
        }

        // execute HTTP request
        final Header requestContentTypeHeader = httpEntityRequest.getFirstHeader(HttpHeaders.CONTENT_TYPE);
        final ContentType requestContentType = requestContentTypeHeader != null
                ? ContentType.parse(requestContentTypeHeader.getValue())
                : contentType;
        execute(httpEntityRequest, requestContentType, new AbstractFutureCallback<T>(responseHandler) {
            @SuppressWarnings("unchecked")
            @Override
            public void onCompleted(HttpResponse result)
                    throws IOException, EntityProviderException, BatchException, ODataApplicationException {

                // if a entity is created (via POST request) the response body contains the new created entity
                HttpStatusCodes statusCode = HttpStatusCodes
                        .fromStatusCode(result.getStatusLine().getStatusCode());

                // look for no content, or no response body!!!
                final boolean noEntity = result.getEntity() == null
                        || result.getEntity().getContentLength() == 0;
                if (statusCode == HttpStatusCodes.NO_CONTENT || noEntity) {
                    responseHandler.onResponse(
                            (T) HttpStatusCodes.fromStatusCode(result.getStatusLine().getStatusCode()));
                } else {

                    switch (uriInfo.getUriType()) {
                    case URI9:
                        // $batch
                        final List<BatchSingleResponse> singleResponses = EntityProvider.parseBatchResponse(
                                result.getEntity().getContent(),
                                result.getFirstHeader(HttpHeaders.CONTENT_TYPE).getValue());

                        // parse batch response bodies
                        final List<Olingo2BatchResponse> responses = new ArrayList<Olingo2BatchResponse>();
                        Map<String, String> contentIdLocationMap = new HashMap<String, String>();

                        final List<Olingo2BatchRequest> batchRequests = (List<Olingo2BatchRequest>) content;
                        final Iterator<Olingo2BatchRequest> iterator = batchRequests.iterator();

                        for (BatchSingleResponse response : singleResponses) {
                            final Olingo2BatchRequest request = iterator.next();

                            if (request instanceof Olingo2BatchChangeRequest
                                    && ((Olingo2BatchChangeRequest) request).getContentId() != null) {

                                contentIdLocationMap.put(
                                        "$" + ((Olingo2BatchChangeRequest) request).getContentId(),
                                        response.getHeader(HttpHeaders.LOCATION));
                            }

                            try {
                                responses.add(parseResponse(edm, contentIdLocationMap, request, response));
                            } catch (Exception e) {
                                // report any parsing errors as error response
                                responses.add(new Olingo2BatchResponse(
                                        Integer.parseInt(response.getStatusCode()), response.getStatusInfo(),
                                        response.getContentId(), response.getHeaders(),
                                        new ODataApplicationException(
                                                "Error parsing response for " + request + ": " + e.getMessage(),
                                                Locale.ENGLISH, e)));
                            }
                        }
                        responseHandler.onResponse((T) responses);
                        break;

                    case URI4:
                    case URI5:
                        // simple property
                        // get the response content as Object for $value or Map<String, Object> otherwise
                        final List<EdmProperty> simplePropertyPath = uriInfo.getPropertyPath();
                        final EdmProperty simpleProperty = simplePropertyPath
                                .get(simplePropertyPath.size() - 1);
                        if (uriInfo.isValue()) {
                            responseHandler.onResponse((T) EntityProvider.readPropertyValue(simpleProperty,
                                    result.getEntity().getContent()));
                        } else {
                            responseHandler.onResponse((T) EntityProvider.readProperty(getContentType(),
                                    simpleProperty, result.getEntity().getContent(),
                                    EntityProviderReadProperties.init().build()));
                        }
                        break;

                    case URI3:
                        // complex property
                        // get the response content as Map<String, Object>
                        final List<EdmProperty> complexPropertyPath = uriInfo.getPropertyPath();
                        final EdmProperty complexProperty = complexPropertyPath
                                .get(complexPropertyPath.size() - 1);
                        responseHandler.onResponse((T) EntityProvider.readProperty(getContentType(),
                                complexProperty, result.getEntity().getContent(),
                                EntityProviderReadProperties.init().build()));
                        break;

                    case URI7A:
                        // $links with 0..1 cardinality property
                        // get the response content as String
                        final EdmEntitySet targetLinkEntitySet = uriInfo.getTargetEntitySet();
                        responseHandler.onResponse((T) EntityProvider.readLink(getContentType(),
                                targetLinkEntitySet, result.getEntity().getContent()));
                        break;

                    case URI7B:
                        // $links with * cardinality property
                        // get the response content as java.util.List<String>
                        final EdmEntitySet targetLinksEntitySet = uriInfo.getTargetEntitySet();
                        responseHandler.onResponse((T) EntityProvider.readLinks(getContentType(),
                                targetLinksEntitySet, result.getEntity().getContent()));
                        break;

                    case URI1:
                    case URI2:
                    case URI6A:
                    case URI6B:
                        // Entity
                        // get the response content as an ODataEntry object
                        responseHandler.onResponse((T) EntityProvider.readEntry(response.getContentHeader(),
                                uriInfo.getTargetEntitySet(), result.getEntity().getContent(),
                                EntityProviderReadProperties.init().build()));
                        break;

                    default:
                        throw new ODataApplicationException(
                                "Unsupported resource type " + uriInfo.getTargetType(), Locale.ENGLISH);
                    }

                }
            }
        });
    } catch (ODataException e) {
        responseHandler.onException(e);
    } catch (URISyntaxException e) {
        responseHandler.onException(e);
    } catch (UnsupportedEncodingException e) {
        responseHandler.onException(e);
    } catch (IOException e) {
        responseHandler.onException(e);
    }
}

From source file:net.rcarz.jiraclient.RestClient.java

private JSON request(HttpEntityEnclosingRequestBase req, Issue.NewAttachment... attachments)
        throws RestException, IOException {
    if (attachments != null) {
        req.setHeader("X-Atlassian-Token", "nocheck");
        MultipartEntity ent = new MultipartEntity();
        for (Issue.NewAttachment attachment : attachments) {
            String filename = attachment.getFilename();
            Object content = attachment.getContent();
            if (content instanceof byte[]) {
                ent.addPart("file", new ByteArrayBody((byte[]) content, filename));
            } else if (content instanceof InputStream) {
                ent.addPart("file", new InputStreamBody((InputStream) content, filename));
            } else if (content instanceof File) {
                ent.addPart("file", new FileBody((File) content, filename));
            } else if (content == null) {
                throw new IllegalArgumentException("Missing content for the file " + filename);
            } else {
                throw new IllegalArgumentException(
                        "Expected file type byte[], java.io.InputStream or java.io.File but provided "
                                + content.getClass().getName() + " for the file " + filename);
            }//  www .j av  a2  s. c o  m
        }
        req.setEntity(ent);
    }
    return request(req);
}

From source file:org.opencastproject.workflow.handler.HttpNotificationWorkflowOperationHandler.java

/**
 * {@inheritDoc}/*  w  w w  . j  av  a 2s .  co m*/
 *
 * @see org.opencastproject.workflow.handler.ResumableWorkflowOperationHandlerBase#start(org.opencastproject.workflow.api.WorkflowInstance,
 *      JobContext)
 */
@Override
public WorkflowOperationResult start(WorkflowInstance workflowInstance, JobContext context)
        throws WorkflowOperationException {
    logger.debug("Running HTTP notification workflow operation on workflow {}", workflowInstance.getId());

    String urlPath = null;
    int maxRetry = DEFAULT_MAX_RETRY;
    int timeout = DEFAULT_TIMEOUT;

    Option<String> notificationSubjectOpt = getCfg(workflowInstance, OPT_NOTIFICATION_SUBJECT);
    Option<String> notificationMessageOpt = getCfg(workflowInstance, OPT_NOTIFICATION_MESSAGE);
    Option<String> methodOpt = getCfg(workflowInstance, OPT_METHOD);
    Option<String> urlPathOpt = getCfg(workflowInstance, OPT_URL_PATH);
    Option<String> maxRetryOpt = getCfg(workflowInstance, OPT_MAX_RETRY);
    Option<String> timeoutOpt = getCfg(workflowInstance, OPT_TIMEOUT);

    // Make sure that at least the url has been set.
    try {
        urlPath = urlPathOpt.get();
    } catch (IllegalStateException e) {
        throw new WorkflowOperationException(format(
                "The %s configuration key is a required parameter for the HTTP notification workflow operation.",
                OPT_URL_PATH));
    }

    // If set, convert the timeout to milliseconds
    if (timeoutOpt.isSome())
        timeout = Integer.parseInt(StringUtils.trimToNull(timeoutOpt.get())) * 1000;

    // Is there a need to retry on failure?
    if (maxRetryOpt.isSome())
        maxRetry = Integer.parseInt(StringUtils.trimToNull(maxRetryOpt.get()));

    // Figure out which request method to use
    HttpEntityEnclosingRequestBase request = null;
    if (methodOpt.isSome()) {
        if ("post".equalsIgnoreCase(methodOpt.get())) {
            logger.debug("Request will be sent using the 'post' method");
            request = new HttpPost(urlPath);
        } else if ("put".equalsIgnoreCase(methodOpt.get())) {
            logger.debug("Request will be sent using the 'put' method");
            request = new HttpPut(urlPath);
        } else
            throw new WorkflowOperationException(
                    "The configuration key '" + OPT_METHOD + "' only supports 'post' and 'put'");
    } else {
        logger.debug("Request will be sent using the default method 'post'");
        request = new HttpPost(urlPath);
    }

    // Add event parameters as form parameters
    try {
        List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();

        // Add the subject (if specified)
        if (notificationSubjectOpt.isSome())
            params.add(new BasicNameValuePair(HTTP_PARAM_SUBJECT, notificationSubjectOpt.get()));

        // Add the message (if specified)
        if (notificationMessageOpt.isSome())
            params.add(new BasicNameValuePair(HTTP_PARAM_MESSAGE, notificationMessageOpt.get()));

        // Add the workflow instance id
        params.add(new BasicNameValuePair(HTTP_PARAM_WORKFLOW, Long.toString(workflowInstance.getId())));

        request.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
    } catch (UnsupportedEncodingException e) {
        throw new WorkflowOperationException(
                "Error happened during the encoding of the event parameter as form parameter: {}", e);
    }

    // Execute the request
    if (!executeRequest(request, maxRetry, timeout, INITIAL_SLEEP_TIME)) {
        throw new WorkflowOperationException(format("Notification could not be delivered to %s", urlPath));
    }

    return createResult(workflowInstance.getMediaPackage(), Action.CONTINUE);
}