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:org.r10r.doctester.testbrowser.TestBrowserImpl.java

private Response makePatchPostOrPutRequest(Request httpRequest) {

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

    try {

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

        HttpEntityEnclosingRequestBase apacheHttpRequest;

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

            apacheHttpRequest = new HttpPatch(httpRequest.uri);

        } else 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 PATCH, POST or PUT request in TestBrowser", e);
        throw new RuntimeException(e);
    }

    return response;

}

From source file:com.cloudmine.api.rest.CMWebService.java

protected void addJson(HttpEntityEnclosingRequestBase message, String json) {
    if (json == null)
        json = JsonUtilities.EMPTY_JSON;
    if (!message.containsHeader(JSON_HEADER.getName())) {
        message.addHeader(JSON_HEADER);/*from w  w  w .  j a  v  a2s . co m*/
    }
    try {
        message.setEntity(new StringEntity(json, JSON_ENCODING));
    } catch (UnsupportedEncodingException e) {
        LOG.error("Error encoding json", e);
    }
}

From source file:org.brutusin.rpc.client.http.HttpEndpoint.java

private CloseableHttpResponse doExec(String serviceId, JsonNode input, HttpMethod httpMethod,
        final ProgressCallback progressCallback) throws IOException {
    RpcRequest request = new RpcRequest();
    request.setJsonrpc("2.0");
    request.setMethod(serviceId);/*from   w  ww. jav  a  2s.  c  o  m*/
    request.setParams(input);
    final String payload = JsonCodec.getInstance().transform(request);
    final HttpUriRequest req;
    if (httpMethod == HttpMethod.GET) {
        String urlparam = URLEncoder.encode(payload, "UTF-8");
        req = new HttpGet(this.endpoint + "?jsonrpc=" + urlparam);
    } else {
        HttpEntityEnclosingRequestBase reqBase;
        if (httpMethod == HttpMethod.POST) {
            reqBase = new HttpPost(this.endpoint);
        } else if (httpMethod == HttpMethod.PUT) {
            reqBase = new HttpPut(this.endpoint);
        } else {
            throw new AssertionError();
        }
        req = reqBase;
        HttpEntity entity;
        Map<String, InputStream> files = JsonCodec.getInstance().getStreams(input);
        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        builder.setMode(HttpMultipartMode.STRICT);
        builder.addPart("jsonrpc", new StringBody(payload, ContentType.APPLICATION_JSON));
        if (files != null && !files.isEmpty()) {
            files = sortFiles(files);
            for (Map.Entry<String, InputStream> entrySet : files.entrySet()) {
                String key = entrySet.getKey();
                InputStream is = entrySet.getValue();
                if (is instanceof MetaDataInputStream) {
                    MetaDataInputStream mis = (MetaDataInputStream) is;
                    builder.addPart(key, new InputStreamBody(mis, mis.getName()));
                } else {
                    builder.addPart(key, new InputStreamBody(is, key));
                }
            }
        }
        entity = builder.build();
        if (progressCallback != null) {
            entity = new ProgressHttpEntityWrapper(entity, progressCallback);
        }
        reqBase.setEntity(entity);
    }
    HttpClientContext context = contexts.get();
    if (this.clientContextFactory != null && context == null) {
        context = clientContextFactory.create();
        contexts.set(context);
    }
    return this.httpClient.execute(req, context);
}

From source file:eu.fusepool.p3.proxy.ProxyHandler.java

@Override
public void handle(String target, Request baseRequest, final HttpServletRequest inRequest,
        final HttpServletResponse outResponse) throws IOException, ServletException {
    final String targetUriString = targetBaseUri + inRequest.getRequestURI();
    final String requestUri = getFullRequestUrl(inRequest);
    //System.out.println(targetUriString);
    final URI targetUri;
    try {//from   ww w.j a  v  a2s . co m
        targetUri = new URI(targetUriString);
    } catch (URISyntaxException ex) {
        throw new IOException(ex);
    }
    final String method = inRequest.getMethod();
    final HttpEntityEnclosingRequestBase outRequest = new HttpEntityEnclosingRequestBase() {

        @Override
        public String getMethod() {
            return method;
        }

    };
    outRequest.setURI(targetUri);
    String transformerUri = null;
    if (method.equals("POST")) {
        if (!"no-transform".equals(inRequest.getHeader("X-Fusepool-Proxy"))) {
            transformerUri = getTransformerUrl(requestUri);
        }
    }
    final Enumeration<String> headerNames = baseRequest.getHeaderNames();
    while (headerNames.hasMoreElements()) {
        final String headerName = headerNames.nextElement();
        if (headerName.equalsIgnoreCase("Content-Length") || headerName.equalsIgnoreCase("X-Fusepool-Proxy")
                || headerName.equalsIgnoreCase("Transfer-Encoding")) {
            continue;
        }
        final Enumeration<String> headerValues = baseRequest.getHeaders(headerName);
        if (headerValues.hasMoreElements()) {
            final String headerValue = headerValues.nextElement();
            outRequest.setHeader(headerName, headerValue);
        }
        while (headerValues.hasMoreElements()) {
            final String headerValue = headerValues.nextElement();
            outRequest.addHeader(headerName, headerValue);
        }
    }
    final Header[] outRequestHeaders = outRequest.getAllHeaders();
    //slow: outRequest.setEntity(new InputStreamEntity(inRequest.getInputStream()));
    final byte[] inEntityBytes = IOUtils.toByteArray(inRequest.getInputStream());
    if (inEntityBytes.length > 0) {
        outRequest.setEntity(new ByteArrayEntity(inEntityBytes));
    }
    final CloseableHttpResponse inResponse = httpclient.execute(outRequest);
    try {
        outResponse.setStatus(inResponse.getStatusLine().getStatusCode());
        final Header[] inResponseHeaders = inResponse.getAllHeaders();
        final Set<String> setHeaderNames = new HashSet();
        for (Header header : inResponseHeaders) {
            if (setHeaderNames.add(header.getName())) {
                outResponse.setHeader(header.getName(), header.getValue());
            } else {
                outResponse.addHeader(header.getName(), header.getValue());
            }
        }
        final HttpEntity entity = inResponse.getEntity();
        final ServletOutputStream os = outResponse.getOutputStream();
        if (entity != null) {
            //outResponse.setContentType(target);
            final InputStream instream = entity.getContent();
            try {
                IOUtils.copy(instream, os);
            } finally {
                instream.close();
            }
        }
        //without flushing this and no or too little byte jetty return 404
        os.flush();
    } finally {
        inResponse.close();
    }
    if (transformerUri != null) {
        Header locationHeader = inResponse.getFirstHeader("Location");
        if (locationHeader == null) {
            log.warn("Response to POST request to LDPC contains no Location header. URI: " + targetUriString);
        } else {
            startTransformation(locationHeader.getValue(), requestUri, transformerUri, inEntityBytes,
                    outRequestHeaders);
        }
    }
}

From source file:com.gft.unity.android.AndroidIO.java

private HttpEntityEnclosingRequestBase buildWebRequest(IORequest request, IOService service,
        String requestUriString, String requestMethod) throws UnsupportedEncodingException, URISyntaxException {

    HttpEntityEnclosingRequestBase httpRequest = new HttpAppverse(new URI(requestUriString), requestMethod);

    /*************//from   w  ww  . j  a v  a2 s  .c  o  m
     * adding content as entity, for request methods != GET
     *************/
    if (!requestMethod.equalsIgnoreCase(RequestMethod.GET.toString())) {
        if (request.getContent() != null && request.getContent().length() > 0) {
            httpRequest.setEntity(new StringEntity(request.getContent(), HTTP.UTF_8));
        }
    }

    /*************
     * CONTENT TYPE
     *************/
    String contentType = contentTypes.get(service.getType()).toString();
    if (request.getContentType() != null) {
        contentType = request.getContentType();

    }
    httpRequest.setHeader("Content-Type", contentType);

    /*************
     * CUSTOM HEADERS HANDLING
     *************/
    if (request.getHeaders() != null && request.getHeaders().length > 0) {
        for (IOHeader header : request.getHeaders()) {
            httpRequest.setHeader(header.getName(), header.getValue());
        }
    }

    /*************
     * COOKIES HANDLING
     *************/
    if (request.getSession() != null && request.getSession().getCookies() != null
            && request.getSession().getCookies().length > 0) {
        StringBuffer buffer = new StringBuffer();
        IOCookie[] cookies = request.getSession().getCookies();
        for (int i = 0; i < cookies.length; i++) {
            IOCookie cookie = cookies[i];
            buffer.append(cookie.getName());
            buffer.append("=");
            buffer.append(cookie.getValue());
            if (i + 1 < cookies.length) {
                buffer.append(" ");
            }
        }
        httpRequest.setHeader("Cookie", buffer.toString());
    }

    /*************
     * DEFAULT HEADERS
     *************/
    httpRequest.setHeader("Accept", contentType); // Accept header should be the same as the request content type used (could be override by the request, or use the service default)
    // httpRequest.setHeader("content-length",
    // String.valueOf(request.getContentLength()));
    httpRequest.setHeader("keep-alive", String.valueOf(false));

    // TODO: set conn timeout ???

    /*************
     * setting user-agent
     *************/
    IOperatingSystem system = (IOperatingSystem) AndroidServiceLocator.GetInstance()
            .GetService(AndroidServiceLocator.SERVICE_TYPE_SYSTEM);
    HttpProtocolParams.setUserAgent(httpClient.getParams(), system.GetOSUserAgent());

    return httpRequest;
}

From source file:org.fcrepo.test.api.TestRESTAPI.java

private HttpResponse putOrPost(HttpEntityEnclosingRequestBase method, HttpEntity requestContent,
        boolean authenticate) throws Exception {
    HttpClient client = getClient(false, authenticate);
    if (method == null) {
        throw new IllegalArgumentException("method must be a non-empty value");
    }// w  w w. j  av  a 2 s  .  com

    if (requestContent != null) {
        method.setEntity(requestContent);
    }

    HttpResponse response = client.execute(method);

    return response;
}

From source file:org.rundeck.api.ApiCall.java

private <T> T requestWithEntity(ApiPathBuilder apiPath, Handler<HttpResponse, T> handler,
        HttpEntityEnclosingRequestBase httpPost) {
    if (null != apiPath.getAccept()) {
        httpPost.setHeader("Accept", apiPath.getAccept());
    }/*from w w  w .  j a v  a  2 s. c o  m*/
    // POST a multi-part request, with all attachments
    if (apiPath.getAttachments().size() > 0 || apiPath.getFileAttachments().size() > 0) {
        MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
        multipartEntityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
        ArrayList<File> tempfiles = new ArrayList<>();

        //attach streams
        for (Entry<String, InputStream> attachment : apiPath.getAttachments().entrySet()) {
            if (client.isUseIntermediateStreamFile()) {
                //transfer to file
                File f = copyToTempfile(attachment.getValue());
                multipartEntityBuilder.addBinaryBody(attachment.getKey(), f);
                tempfiles.add(f);
            } else {
                multipartEntityBuilder.addBinaryBody(attachment.getKey(), attachment.getValue());
            }
        }
        if (tempfiles.size() > 0) {
            handler = TempFileCleanupHandler.chain(handler, tempfiles);
        }

        //attach files
        for (Entry<String, File> attachment : apiPath.getFileAttachments().entrySet()) {
            multipartEntityBuilder.addBinaryBody(attachment.getKey(), attachment.getValue());
        }

        httpPost.setEntity(multipartEntityBuilder.build());
    } else if (apiPath.getForm().size() > 0) {
        try {
            httpPost.setEntity(new UrlEncodedFormEntity(apiPath.getForm(), "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            throw new RundeckApiException("Unsupported encoding: " + e.getMessage(), e);
        }
    } else if (apiPath.getContentStream() != null && apiPath.getContentType() != null) {
        if (client.isUseIntermediateStreamFile()) {
            ArrayList<File> tempfiles = new ArrayList<>();
            File f = copyToTempfile(apiPath.getContentStream());
            tempfiles.add(f);
            httpPost.setEntity(new FileEntity(f, ContentType.create(apiPath.getContentType())));

            handler = TempFileCleanupHandler.chain(handler, tempfiles);
        } else {
            InputStreamEntity entity = new InputStreamEntity(apiPath.getContentStream(),
                    ContentType.create(apiPath.getContentType()));
            httpPost.setEntity(entity);
        }
    } else if (apiPath.getContents() != null && apiPath.getContentType() != null) {
        ByteArrayEntity bae = new ByteArrayEntity(apiPath.getContents(),
                ContentType.create(apiPath.getContentType()));

        httpPost.setEntity(bae);
    } else if (apiPath.getContentFile() != null && apiPath.getContentType() != null) {
        httpPost.setEntity(
                new FileEntity(apiPath.getContentFile(), ContentType.create(apiPath.getContentType())));
    } else if (apiPath.getXmlDocument() != null) {
        httpPost.setHeader("Content-Type", "application/xml");
        httpPost.setEntity(new EntityTemplate(new DocumentContentProducer(apiPath.getXmlDocument())));
    } else if (apiPath.isEmptyContent()) {
        //empty content
    } else {
        throw new IllegalArgumentException("No Form or Multipart entity for POST content-body");
    }

    return execute(httpPost, handler);
}

From source file:ch.iterate.openstack.swift.Client.java

public void deleteObjects(Region region, String container, List<String> objects) throws IOException {
    HttpEntityEnclosingRequestBase method = new HttpEntityEnclosingRequestBase() {
        @Override//from   w w  w .j  a  va2s . c  o m
        public String getMethod() {
            return "DELETE";
        }
    };
    // Will delete multiple objects or containers from their account with a
    // single request. Responds to DELETE requests with query parameter
    // ?bulk-delete set.
    LinkedList<NameValuePair> parameters = new LinkedList<NameValuePair>();
    parameters.add(new BasicNameValuePair("bulk-delete", "1"));
    method.setURI(region.getStorageUrl(container, parameters));
    method.setHeader(HttpHeaders.CONTENT_TYPE, "text/plain");
    // Newline separated list of url encoded objects to delete
    StringBuilder body = new StringBuilder();
    for (String object : objects) {
        final String path = region.getStorageUrl(container, object).getRawPath();
        body.append(path.substring(region.getStorageUrl().getRawPath().length()));
    }
    method.setEntity(new StringEntity(body.toString(), "UTF-8"));
    this.execute(method, new DefaultResponseHandler());
}

From source file:anhttpclient.impl.DefaultWebBrowser.java

/**
 * Return {@link HttpRequestBase} from WebRequest which is
 * shell on http POST or PUT request/*w  ww  . j  ava 2  s  .  co m*/
 *
 * @param webRequest shell under http POST request
 * @param httpRequest HttpEntityEnclosingRequestBase instance
 * @return HttpMethodBase for specified shell on http POST request
 */
private HttpRequestBase populateHttpEntityEnclosingRequestBaseMethod(WebRequest webRequest,
        HttpEntityEnclosingRequestBase httpRequest) {

    EntityEnclosingWebRequest webRequestWithBody = (EntityEnclosingWebRequest) webRequest;
    setDefaultMethodParams(httpRequest);
    setHeaders(httpRequest, webRequestWithBody.getHeaders());

    HttpEntity entity = null;

    if (webRequestWithBody.getFormParams() != null && webRequestWithBody.getFormParams().size() > 0) {

        StringBuilder contentType = (new StringBuilder(HttpConstants.MIME_FORM_ENCODED)).append("; charset=")
                .append(webRequestWithBody.getFormParamsCharset());

        httpRequest.addHeader(HTTP.CONTENT_TYPE, contentType.toString());

        // data - name/value params
        List<NameValuePair> nameValuePairList = null;
        Map<String, String> requestParams = webRequestWithBody.getFormParams();
        if ((requestParams != null) && (requestParams.size() > 0)) {
            nameValuePairList = new ArrayList<NameValuePair>();
            for (Map.Entry<String, String> entry : requestParams.entrySet()) {
                nameValuePairList.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
            }
        }

        if (nameValuePairList != null) {
            try {
                entity = new UrlEncodedFormEntity(nameValuePairList, HTTP.UTF_8);
            } catch (UnsupportedEncodingException e) {
                throw new RuntimeException(e);
            }
        }
    } else if (webRequestWithBody.getParts().size() > 0) {
        entity = new MultipartEntity();
        for (Map.Entry<String, ContentBody> entry : webRequestWithBody.getParts().entrySet()) {
            ((MultipartEntity) entity).addPart(entry.getKey(), entry.getValue());
        }
    }

    if (entity != null) {
        httpRequest.setEntity(entity);
    }

    return httpRequest;
}