Search in sources :

Example 1 with EntityEnclosingMethod

use of org.apache.commons.httpclient.methods.EntityEnclosingMethod in project camel by apache.

the class HttpProducer method createMethod.

/**
     * Creates the HttpMethod to use to call the remote server, either its GET or POST.
     *
     * @param exchange the exchange
     * @return the created method as either GET or POST
     * @throws CamelExchangeException is thrown if error creating RequestEntity
     */
@SuppressWarnings("deprecation")
protected HttpMethod createMethod(Exchange exchange) throws Exception {
    // creating the url to use takes 2-steps
    String url = HttpHelper.createURL(exchange, getEndpoint());
    URI uri = HttpHelper.createURI(exchange, url, getEndpoint());
    // get the url and query string from the uri
    url = uri.toASCIIString();
    String queryString = uri.getRawQuery();
    // execute any custom url rewrite
    String rewriteUrl = HttpHelper.urlRewrite(exchange, url, getEndpoint(), this);
    if (rewriteUrl != null) {
        // update url and query string from the rewritten url
        url = rewriteUrl;
        uri = new URI(url);
        // use raw query to have uri decimal encoded which http client requires
        queryString = uri.getRawQuery();
    }
    // remove query string as http client does not accept that
    if (url.indexOf('?') != -1) {
        url = url.substring(0, url.indexOf('?'));
    }
    // create http holder objects for the request
    RequestEntity requestEntity = createRequestEntity(exchange);
    String methodName = HttpHelper.createMethod(exchange, getEndpoint(), requestEntity != null).name();
    HttpMethods methodsToUse = HttpMethods.valueOf(methodName);
    HttpMethod method = methodsToUse.createMethod(url);
    if (queryString != null) {
        // need to encode query string
        queryString = UnsafeUriCharactersEncoder.encode(queryString);
        method.setQueryString(queryString);
    }
    LOG.trace("Using URL: {} with method: {}", url, method);
    if (methodsToUse.isEntityEnclosing()) {
        ((EntityEnclosingMethod) method).setRequestEntity(requestEntity);
        if (requestEntity != null && requestEntity.getContentType() == null) {
            LOG.debug("No Content-Type provided for URL: {} with exchange: {}", url, exchange);
        }
    }
    // there must be a host on the method
    if (method.getHostConfiguration().getHost() == null) {
        throw new IllegalArgumentException("Invalid uri: " + url + ". If you are forwarding/bridging http endpoints, then enable the bridgeEndpoint option on the endpoint: " + getEndpoint());
    }
    return method;
}
Also used : EntityEnclosingMethod(org.apache.commons.httpclient.methods.EntityEnclosingMethod) FileRequestEntity(org.apache.commons.httpclient.methods.FileRequestEntity) ByteArrayRequestEntity(org.apache.commons.httpclient.methods.ByteArrayRequestEntity) InputStreamRequestEntity(org.apache.commons.httpclient.methods.InputStreamRequestEntity) StringRequestEntity(org.apache.commons.httpclient.methods.StringRequestEntity) RequestEntity(org.apache.commons.httpclient.methods.RequestEntity) URI(java.net.URI) HttpMethod(org.apache.commons.httpclient.HttpMethod)

Example 2 with EntityEnclosingMethod

use of org.apache.commons.httpclient.methods.EntityEnclosingMethod in project pinot by linkedin.

the class FileUploadUtils method sendSegmentUriImpl.

private static int sendSegmentUriImpl(final String host, final String port, final String uri) {
    SendFileMethod httpMethod = SendFileMethod.POST;
    EntityEnclosingMethod method = null;
    try {
        method = httpMethod.forUri("http://" + host + ":" + port + "/" + SEGMENTS_PATH);
        method.setRequestHeader(UPLOAD_TYPE, FileUploadType.URI.toString());
        method.setRequestHeader(DOWNLOAD_URI, uri);
        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 uri: {}", uri, e);
        Utils.rethrowException(e);
        throw new AssertionError("Should not reach this");
    } finally {
        if (method != null) {
            method.releaseConnection();
        }
    }
}
Also used : EntityEnclosingMethod(org.apache.commons.httpclient.methods.EntityEnclosingMethod) HttpException(org.apache.commons.httpclient.HttpException) HttpException(org.apache.commons.httpclient.HttpException) IOException(java.io.IOException)

Example 3 with EntityEnclosingMethod

use of org.apache.commons.httpclient.methods.EntityEnclosingMethod in project pinot by linkedin.

the class FileUploadUtils method sendFile.

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 {
        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();
        }
    }
}
Also used : PartSource(org.apache.commons.httpclient.methods.multipart.PartSource) BufferedInputStream(java.io.BufferedInputStream) FilePart(org.apache.commons.httpclient.methods.multipart.FilePart) Part(org.apache.commons.httpclient.methods.multipart.Part) EntityEnclosingMethod(org.apache.commons.httpclient.methods.EntityEnclosingMethod) HttpException(org.apache.commons.httpclient.HttpException) HttpMethodParams(org.apache.commons.httpclient.params.HttpMethodParams) MultipartRequestEntity(org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity) FilePart(org.apache.commons.httpclient.methods.multipart.FilePart) HttpException(org.apache.commons.httpclient.HttpException) IOException(java.io.IOException)

Example 4 with EntityEnclosingMethod

use of org.apache.commons.httpclient.methods.EntityEnclosingMethod in project pinpoint by naver.

the class HttpMethodBaseExecuteMethodInterceptor method recordEntity.

private void recordEntity(HttpMethod httpMethod, Trace trace) {
    if (httpMethod instanceof EntityEnclosingMethod) {
        final EntityEnclosingMethod entityEnclosingMethod = (EntityEnclosingMethod) httpMethod;
        final RequestEntity entity = entityEnclosingMethod.getRequestEntity();
        if (entity != null && entity.isRepeatable() && entity.getContentLength() > 0) {
            if (entitySampler.isSampling()) {
                try {
                    String entityValue;
                    String charSet = entityEnclosingMethod.getRequestCharSet();
                    if (charSet == null || charSet.isEmpty()) {
                        charSet = HttpConstants.DEFAULT_CONTENT_CHARSET;
                    }
                    if (entity instanceof ByteArrayRequestEntity || entity instanceof StringRequestEntity) {
                        entityValue = entityUtilsToString(entity, charSet);
                    } else {
                        entityValue = entity.getClass() + " (ContentType:" + entity.getContentType() + ")";
                    }
                    final SpanEventRecorder recorder = trace.currentSpanEventRecorder();
                    recorder.recordAttribute(AnnotationKey.HTTP_PARAM_ENTITY, entityValue);
                } catch (Exception e) {
                    logger.debug("HttpEntityEnclosingRequest entity record fail. Caused:{}", e.getMessage(), e);
                }
            }
        }
    }
}
Also used : StringRequestEntity(org.apache.commons.httpclient.methods.StringRequestEntity) EntityEnclosingMethod(org.apache.commons.httpclient.methods.EntityEnclosingMethod) SpanEventRecorder(com.navercorp.pinpoint.bootstrap.context.SpanEventRecorder) ByteArrayRequestEntity(org.apache.commons.httpclient.methods.ByteArrayRequestEntity) StringRequestEntity(org.apache.commons.httpclient.methods.StringRequestEntity) RequestEntity(org.apache.commons.httpclient.methods.RequestEntity) URIException(org.apache.commons.httpclient.URIException) ByteArrayRequestEntity(org.apache.commons.httpclient.methods.ByteArrayRequestEntity)

Example 5 with EntityEnclosingMethod

use of org.apache.commons.httpclient.methods.EntityEnclosingMethod in project openhab1-addons by openhab.

the class AbstractRequest method executeUrl.

/**
     * Executes the given <code>url</code> with the given <code>httpMethod</code>. In the case of httpMethods that do
     * not support automatic redirection, manually handle the HTTP temporary redirect (307) and retry with the new URL.
     * 
     * @param httpMethod
     *            the HTTP method to use
     * @param url
     *            the url to execute (in milliseconds)
     * @param contentString
     *            the content to be sent to the given <code>url</code> or <code>null</code> if no content should be
     *            sent.
     * @param contentType
     *            the content type of the given <code>contentString</code>
     * @return the response body or <code>NULL</code> when the request went wrong
     */
protected final String executeUrl(final String httpMethod, final String url, final String contentString, final String contentType) {
    HttpClient client = new HttpClient();
    HttpMethod method = HttpUtil.createHttpMethod(httpMethod, url);
    method.getParams().setSoTimeout(httpRequestTimeout);
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false));
    for (String httpHeaderKey : HTTP_HEADERS.stringPropertyNames()) {
        method.addRequestHeader(new Header(httpHeaderKey, HTTP_HEADERS.getProperty(httpHeaderKey)));
    }
    // add content if a valid method is given ...
    if (method instanceof EntityEnclosingMethod && contentString != null) {
        EntityEnclosingMethod eeMethod = (EntityEnclosingMethod) method;
        InputStream content = new ByteArrayInputStream(contentString.getBytes());
        eeMethod.setRequestEntity(new InputStreamRequestEntity(content, contentType));
    }
    if (logger.isDebugEnabled()) {
        try {
            logger.trace("About to execute '" + method.getURI().toString() + "'");
        } catch (URIException e) {
            logger.trace(e.getMessage());
        }
    }
    try {
        int statusCode = client.executeMethod(method);
        if (statusCode == HttpStatus.SC_NO_CONTENT || statusCode == HttpStatus.SC_ACCEPTED) {
            // perfectly fine but we cannot expect any answer...
            return null;
        }
        // Manually handle 307 redirects with a little tail recursion
        if (statusCode == HttpStatus.SC_TEMPORARY_REDIRECT) {
            Header[] headers = method.getResponseHeaders("Location");
            String newUrl = headers[headers.length - 1].getValue();
            return executeUrl(httpMethod, newUrl, contentString, contentType);
        }
        if (statusCode != HttpStatus.SC_OK) {
            logger.warn("Method failed: " + method.getStatusLine());
        }
        InputStream tmpResponseStream = method.getResponseBodyAsStream();
        Header encodingHeader = method.getResponseHeader("Content-Encoding");
        if (encodingHeader != null) {
            for (HeaderElement ehElem : encodingHeader.getElements()) {
                if (ehElem.toString().matches(".*gzip.*")) {
                    tmpResponseStream = new GZIPInputStream(tmpResponseStream);
                    logger.trace("GZipped InputStream from {}", url);
                } else if (ehElem.toString().matches(".*deflate.*")) {
                    tmpResponseStream = new InflaterInputStream(tmpResponseStream);
                    logger.trace("Deflated InputStream from {}", url);
                }
            }
        }
        String responseBody = IOUtils.toString(tmpResponseStream);
        if (!responseBody.isEmpty()) {
            logger.trace(responseBody);
        }
        return responseBody;
    } catch (HttpException he) {
        logger.error("Fatal protocol violation: {}", he.toString());
    } catch (IOException ioe) {
        logger.error("Fatal transport error: {}", ioe.toString());
    } finally {
        method.releaseConnection();
    }
    return null;
}
Also used : InputStreamRequestEntity(org.apache.commons.httpclient.methods.InputStreamRequestEntity) GZIPInputStream(java.util.zip.GZIPInputStream) InflaterInputStream(java.util.zip.InflaterInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) HeaderElement(org.apache.commons.httpclient.HeaderElement) InflaterInputStream(java.util.zip.InflaterInputStream) EntityEnclosingMethod(org.apache.commons.httpclient.methods.EntityEnclosingMethod) DefaultHttpMethodRetryHandler(org.apache.commons.httpclient.DefaultHttpMethodRetryHandler) IOException(java.io.IOException) GZIPInputStream(java.util.zip.GZIPInputStream) URIException(org.apache.commons.httpclient.URIException) Header(org.apache.commons.httpclient.Header) ByteArrayInputStream(java.io.ByteArrayInputStream) HttpClient(org.apache.commons.httpclient.HttpClient) HttpException(org.apache.commons.httpclient.HttpException) HttpMethod(org.apache.commons.httpclient.HttpMethod)

Aggregations

EntityEnclosingMethod (org.apache.commons.httpclient.methods.EntityEnclosingMethod)10 HttpMethod (org.apache.commons.httpclient.HttpMethod)6 IOException (java.io.IOException)4 HttpException (org.apache.commons.httpclient.HttpException)4 URIException (org.apache.commons.httpclient.URIException)4 ByteArrayRequestEntity (org.apache.commons.httpclient.methods.ByteArrayRequestEntity)4 StringRequestEntity (org.apache.commons.httpclient.methods.StringRequestEntity)4 HttpClient (org.apache.commons.httpclient.HttpClient)3 RequestEntity (org.apache.commons.httpclient.methods.RequestEntity)3 HttpMethodParams (org.apache.commons.httpclient.params.HttpMethodParams)3 Pattern (java.util.regex.Pattern)2 DefaultHttpMethodRetryHandler (org.apache.commons.httpclient.DefaultHttpMethodRetryHandler)2 Header (org.apache.commons.httpclient.Header)2 URI (org.apache.commons.httpclient.URI)2 InputStreamRequestEntity (org.apache.commons.httpclient.methods.InputStreamRequestEntity)2 SpanEventRecorder (com.navercorp.pinpoint.bootstrap.context.SpanEventRecorder)1 BufferedInputStream (java.io.BufferedInputStream)1 ByteArrayInputStream (java.io.ByteArrayInputStream)1 InputStream (java.io.InputStream)1 ConnectException (java.net.ConnectException)1