Example usage for org.apache.commons.httpclient.methods EntityEnclosingMethod setRequestEntity

List of usage examples for org.apache.commons.httpclient.methods EntityEnclosingMethod setRequestEntity

Introduction

In this page you can find the example usage for org.apache.commons.httpclient.methods EntityEnclosingMethod setRequestEntity.

Prototype

public void setRequestEntity(RequestEntity paramRequestEntity) 

Source Link

Usage

From source file:lucee.commons.net.http.httpclient3.HttpMethodCloner.java

private static void copyEntityEnclosingMethod(EntityEnclosingMethod m, EntityEnclosingMethod copy) {
    copy.setRequestEntity(m.getRequestEntity());
}

From source file:lucee.commons.net.http.httpclient3.HTTPEngine3Impl.java

private static void setBody(EntityEnclosingMethod httpMethod, Object body) throws IOException {
    if (body != null)
        try {//from  w w  w. j  a  v  a2  s.  com
            httpMethod.setRequestEntity(toRequestEntity(body));
        } catch (PageException e) {
            throw ExceptionUtil.toIOException(e);
        }
}

From source file:it.geosolutions.figis.requester.HTTPUtils.java

/**
* Send an HTTP request (PUT or POST) to a server.
* <BR>Basic auth is used if both username and pw are not null.
* <P>//from   www . j  av a2s .co m
* Only <UL>
* <LI>200: OK</LI>
* <LI>201: ACCEPTED</LI>
* <LI>202: CREATED</LI>
* </UL> are accepted as successful codes; in these cases the response string will be returned.
*
* @return the HTTP response or <TT>null</TT> on errors.
*/
private static String send(final EntityEnclosingMethod httpMethod, String url, RequestEntity requestEntity,
        String username, String pw) {

    try {
        HttpClient client = new HttpClient();
        setAuth(client, url, username, pw);
        client.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
        if (requestEntity != null) {
            httpMethod.setRequestEntity(requestEntity);
        }

        int status = client.executeMethod(httpMethod);

        switch (status) {
        case HttpURLConnection.HTTP_OK:
        case HttpURLConnection.HTTP_CREATED:
        case HttpURLConnection.HTTP_ACCEPTED:

            String response = IOUtils.toString(httpMethod.getResponseBodyAsStream());
            if (LOGGER.isInfoEnabled()) {
                LOGGER.info("HTTP " + httpMethod.getStatusText() + ": " + response);
            }
            return response;
        default:
            LOGGER.warn("Bad response: code[" + status + "]" + " msg[" + httpMethod.getStatusText() + "]"
                    + " url[" + url + "]" + " method[" + httpMethod.getClass().getSimpleName() + "]: "
                    + IOUtils.toString(httpMethod.getResponseBodyAsStream()));

            return null;
        }
    } catch (ConnectException e) {
        LOGGER.error("Couldn't connect to [" + url + "]", e);

        return null;
    } catch (IOException e) {
        LOGGER.error("Error talking to " + url + " : " + e.getLocalizedMessage(), e);

        return null;
    } finally {
        if (httpMethod != null) {
            httpMethod.releaseConnection();
        }
    }
}

From source file:com.linkedin.pinot.common.utils.FileUploadUtils.java

public static int sendFile(final String host, final String port, final String path, final String fileName,
        final InputStream inputStream, final long lengthInBytes, SendFileMethod httpMethod) {
    EntityEnclosingMethod method = null;
    try {//from  ww w .  ja  va  2s  . co m
        method = httpMethod.forUri("http://" + host + ":" + port + "/" + path);
        Part[] parts = { new FilePart(fileName, new PartSource() {
            @Override
            public long getLength() {
                return lengthInBytes;
            }

            @Override
            public String getFileName() {
                return "fileName";
            }

            @Override
            public InputStream createInputStream() throws IOException {
                return new BufferedInputStream(inputStream);
            }
        }) };
        method.setRequestEntity(new MultipartRequestEntity(parts, new HttpMethodParams()));
        FILE_UPLOAD_HTTP_CLIENT.executeMethod(method);
        if (method.getStatusCode() >= 400) {
            String errorString = "POST Status Code: " + method.getStatusCode() + "\n";
            if (method.getResponseHeader("Error") != null) {
                errorString += "ServletException: " + method.getResponseHeader("Error").getValue();
            }
            throw new HttpException(errorString);
        }
        return method.getStatusCode();
    } catch (Exception e) {
        LOGGER.error("Caught exception while sending file: {}", fileName, e);
        Utils.rethrowException(e);
        throw new AssertionError("Should not reach this");
    } finally {
        if (method != null) {
            method.releaseConnection();
        }
    }
}

From source file:it.geosolutions.geoserver.rest.HTTPUtils.java

/**
 * Send an HTTP request (PUT or POST) to a server. <BR>
 * Basic auth is used if both username and pw are not null.
 * <P>//from  ww  w .  jav  a2s.c  om
 * Only
 * <UL>
 * <LI>200: OK</LI>
 * <LI>201: ACCEPTED</LI>
 * <LI>202: CREATED</LI>
 * </UL>
 * are accepted as successful codes; in these cases the response string will
 * be returned.
 * 
 * @return the HTTP response or <TT>null</TT> on errors.
 */
private static String send(final EntityEnclosingMethod httpMethod, String url, RequestEntity requestEntity,
        String username, String pw) {
    HttpClient client = new HttpClient();
    HttpConnectionManager connectionManager = client.getHttpConnectionManager();
    try {
        setAuth(client, url, username, pw);
        connectionManager.getParams().setConnectionTimeout(5000);
        if (requestEntity != null)
            httpMethod.setRequestEntity(requestEntity);
        int status = client.executeMethod(httpMethod);

        switch (status) {
        case HttpURLConnection.HTTP_OK:
        case HttpURLConnection.HTTP_CREATED:
        case HttpURLConnection.HTTP_ACCEPTED:
            String response = IOUtils.toString(httpMethod.getResponseBodyAsStream());
            // LOGGER.info("================= POST " + url);
            if (LOGGER.isInfoEnabled())
                LOGGER.info("HTTP " + httpMethod.getStatusText() + ": " + response);
            return response;
        default:
            LOGGER.warn("Bad response: code[" + status + "]" + " msg[" + httpMethod.getStatusText() + "]"
                    + " url[" + url + "]" + " method[" + httpMethod.getClass().getSimpleName() + "]: "
                    + IOUtils.toString(httpMethod.getResponseBodyAsStream()));
            return null;
        }
    } catch (ConnectException e) {
        LOGGER.info("Couldn't connect to [" + url + "]");
        return null;
    } catch (IOException e) {
        LOGGER.error("Error talking to " + url + " : " + e.getLocalizedMessage());
        return null;
    } finally {
        if (httpMethod != null)
            httpMethod.releaseConnection();
        connectionManager.closeIdleConnections(0);
    }
}

From source file:jails.http.client.CommonsClientHttpRequest.java

@Override
public ClientHttpResponse executeInternal(HttpHeaders headers, byte[] output) throws IOException {
    for (Map.Entry<String, List<String>> entry : headers.entrySet()) {
        String headerName = entry.getKey();
        for (String headerValue : entry.getValue()) {
            httpMethod.addRequestHeader(headerName, headerValue);
        }//  w  w w  . j  a  v a  2s.c o m
    }
    if (this.httpMethod instanceof EntityEnclosingMethod) {
        EntityEnclosingMethod entityEnclosingMethod = (EntityEnclosingMethod) this.httpMethod;
        RequestEntity requestEntity = new ByteArrayRequestEntity(output);
        entityEnclosingMethod.setRequestEntity(requestEntity);
    }
    this.httpClient.executeMethod(this.httpMethod);
    return new CommonsClientHttpResponse(this.httpMethod);
}

From source file:com.smartitengineering.util.rest.client.jersey.cache.CustomApacheHttpClientResponseResolver.java

private HttpMethod convertRequest(HTTPRequest request) {
    URI requestURI = request.getRequestURI();
    HttpMethod method = getMethod(request.getMethod(), requestURI);
    Headers requestHeaders = request.getAllHeaders();
    addHeaders(requestHeaders, method);//from   w w  w .ja  v a2s  .  com
    method.setDoAuthentication(true);
    if (method instanceof EntityEnclosingMethod && request.hasPayload()) {
        InputStream payload = request.getPayload().getInputStream();
        EntityEnclosingMethod carrier = (EntityEnclosingMethod) method;
        if (payload != null) {
            carrier.setRequestEntity(new InputStreamRequestEntity(payload));
        }
    }

    return method;
}

From source file:edu.internet2.middleware.shibboleth.idp.slo.HTTPClientOutTransportAdapter.java

public HTTPClientOutTransportAdapter(HttpConnection connection, EntityEnclosingMethod method) {
    this.connection = connection;
    this.method = method;
    requestEntity = new SOAPRequestEntity();
    method.setRequestEntity(requestEntity);
}

From source file:com.vmware.aurora.vc.VcFileManager.java

static private void uploadFileWork(String url, boolean isPost, File file, String contentType, String cookie,
        ProgressListener listener) throws Exception {
    EntityEnclosingMethod method;
    final RequestEntity entity = new ProgressListenerRequestEntity(file, contentType, listener);
    if (isPost) {
        method = new PostMethod(url);
        method.setContentChunked(true);/*www.ja  v  a 2s.  c o m*/
    } else {
        method = new PutMethod(url);
        method.addRequestHeader("Cookie", cookie);
        method.setContentChunked(false);
        HttpMethodParams params = new HttpMethodParams();
        params.setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE, true);
        method.setParams(params);
    }
    method.setRequestEntity(entity);

    logger.info("upload " + file + " to " + url);
    long t1 = System.currentTimeMillis();
    boolean ok = false;
    try {
        HttpClient httpClient = new HttpClient();
        int statusCode = httpClient.executeMethod(method);
        String response = method.getResponseBodyAsString(100);
        logger.debug("status: " + statusCode + " response: " + response);
        if (statusCode != HttpStatus.SC_CREATED && statusCode != HttpStatus.SC_OK) {
            throw new Exception("Http post failed");
        }
        method.releaseConnection();
        ok = true;
    } finally {
        if (!ok) {
            method.abort();
        }
    }
    long t2 = System.currentTimeMillis();
    logger.info("upload " + file + " done in " + (t2 - t1) + " ms");
}

From source file:net.oauth.client.httpclient3.HttpClient3.java

public HttpResponseMessage execute(HttpMessage request, Map<String, Object> parameters) throws IOException {
    final String method = request.method;
    final String url = request.url.toExternalForm();
    final InputStream body = request.getBody();
    final boolean isDelete = DELETE.equalsIgnoreCase(method);
    final boolean isPost = POST.equalsIgnoreCase(method);
    final boolean isPut = PUT.equalsIgnoreCase(method);
    byte[] excerpt = null;
    HttpMethod httpMethod;//from   w  w  w .j  a v a  2s  . co m
    if (isPost || isPut) {
        EntityEnclosingMethod entityEnclosingMethod = isPost ? new PostMethod(url) : new PutMethod(url);
        if (body != null) {
            ExcerptInputStream e = new ExcerptInputStream(body);
            String length = request.removeHeaders(HttpMessage.CONTENT_LENGTH);
            entityEnclosingMethod.setRequestEntity((length == null) ? new InputStreamRequestEntity(e)
                    : new InputStreamRequestEntity(e, Long.parseLong(length)));
            excerpt = e.getExcerpt();
        }
        httpMethod = entityEnclosingMethod;
    } else if (isDelete) {
        httpMethod = new DeleteMethod(url);
    } else {
        httpMethod = new GetMethod(url);
    }
    for (Map.Entry<String, Object> p : parameters.entrySet()) {
        String name = p.getKey();
        String value = p.getValue().toString();
        if (FOLLOW_REDIRECTS.equals(name)) {
            httpMethod.setFollowRedirects(Boolean.parseBoolean(value));
        } else if (READ_TIMEOUT.equals(name)) {
            httpMethod.getParams().setIntParameter(HttpMethodParams.SO_TIMEOUT, Integer.parseInt(value));
        }
    }
    for (Map.Entry<String, String> header : request.headers) {
        httpMethod.addRequestHeader(header.getKey(), header.getValue());
    }
    HttpClient client = clientPool.getHttpClient(new URL(httpMethod.getURI().toString()));
    client.executeMethod(httpMethod);
    return new HttpMethodResponse(httpMethod, excerpt, request.getContentCharset());
}