Search in sources :

Example 1 with ByteArrayRequestEntity

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

the class HttpProducer method createRequestEntity.

/**
     * Creates a holder object for the data to send to the remote server.
     *
     * @param exchange the exchange with the IN message with data to send
     * @return the data holder
     * @throws CamelExchangeException is thrown if error creating RequestEntity
     */
protected RequestEntity createRequestEntity(Exchange exchange) throws CamelExchangeException {
    Message in = exchange.getIn();
    if (in.getBody() == null) {
        return null;
    }
    RequestEntity answer = in.getBody(RequestEntity.class);
    if (answer == null) {
        try {
            Object data = in.getBody();
            if (data != null) {
                String contentType = ExchangeHelper.getContentType(exchange);
                if (contentType != null && HttpConstants.CONTENT_TYPE_JAVA_SERIALIZED_OBJECT.equals(contentType)) {
                    if (!getEndpoint().getComponent().isAllowJavaSerializedObject()) {
                        throw new CamelExchangeException("Content-type " + HttpConstants.CONTENT_TYPE_JAVA_SERIALIZED_OBJECT + " is not allowed", exchange);
                    }
                    // serialized java object
                    Serializable obj = in.getMandatoryBody(Serializable.class);
                    // write object to output stream
                    ByteArrayOutputStream bos = new ByteArrayOutputStream();
                    HttpHelper.writeObjectToStream(bos, obj);
                    answer = new ByteArrayRequestEntity(bos.toByteArray(), HttpConstants.CONTENT_TYPE_JAVA_SERIALIZED_OBJECT);
                    IOHelper.close(bos);
                } else if (data instanceof File || data instanceof GenericFile) {
                    // file based (could potentially also be a FTP file etc)
                    File file = in.getBody(File.class);
                    if (file != null) {
                        answer = new FileRequestEntity(file, contentType);
                    }
                } else if (data instanceof String) {
                    // be a bit careful with String as any type can most likely be converted to String
                    // so we only do an instanceof check and accept String if the body is really a String
                    // do not fallback to use the default charset as it can influence the request
                    // (for example application/x-www-form-urlencoded forms being sent)
                    String charset = IOHelper.getCharsetName(exchange, false);
                    answer = new StringRequestEntity((String) data, contentType, charset);
                }
                // fallback as input stream
                if (answer == null) {
                    // force the body as an input stream since this is the fallback
                    InputStream is = in.getMandatoryBody(InputStream.class);
                    answer = new InputStreamRequestEntity(is, contentType);
                }
            }
        } catch (UnsupportedEncodingException e) {
            throw new CamelExchangeException("Error creating RequestEntity from message body", exchange, e);
        } catch (IOException e) {
            throw new CamelExchangeException("Error serializing message body", exchange, e);
        }
    }
    return answer;
}
Also used : CamelExchangeException(org.apache.camel.CamelExchangeException) Serializable(java.io.Serializable) StringRequestEntity(org.apache.commons.httpclient.methods.StringRequestEntity) InputStreamRequestEntity(org.apache.commons.httpclient.methods.InputStreamRequestEntity) Message(org.apache.camel.Message) InputStream(java.io.InputStream) UnsupportedEncodingException(java.io.UnsupportedEncodingException) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException) FileRequestEntity(org.apache.commons.httpclient.methods.FileRequestEntity) 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) GenericFile(org.apache.camel.component.file.GenericFile) File(java.io.File) GenericFile(org.apache.camel.component.file.GenericFile) ByteArrayRequestEntity(org.apache.commons.httpclient.methods.ByteArrayRequestEntity)

Example 2 with ByteArrayRequestEntity

use of org.apache.commons.httpclient.methods.ByteArrayRequestEntity 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 3 with ByteArrayRequestEntity

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

the class KM200Comm method sendDataToService.

/**
     * This function does the SEND http communication to the device
     *
     */
public Integer sendDataToService(String service, byte[] data) {
    // Create an instance of HttpClient.
    Integer rCode = null;
    if (client == null) {
        client = new HttpClient();
    }
    synchronized (client) {
        // Create a method instance.
        PostMethod method = new PostMethod("http://" + device.getIP4Address() + service);
        // Provide custom retry handler is necessary
        method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false));
        // Set the right header
        method.setRequestHeader("Accept", "application/json");
        method.addRequestHeader("User-Agent", "TeleHeater/2.2.3");
        method.setRequestEntity(new ByteArrayRequestEntity(data));
        try {
            rCode = client.executeMethod(method);
        } catch (Exception e) {
            logger.error("Failed to send data {}", e);
        } finally {
            // Release the connection.
            method.releaseConnection();
        }
        return rCode;
    }
}
Also used : PostMethod(org.apache.commons.httpclient.methods.PostMethod) HttpClient(org.apache.commons.httpclient.HttpClient) DefaultHttpMethodRetryHandler(org.apache.commons.httpclient.DefaultHttpMethodRetryHandler) JSONException(org.json.JSONException) GeneralSecurityException(java.security.GeneralSecurityException) HttpException(org.apache.commons.httpclient.HttpException) IOException(java.io.IOException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) ByteArrayRequestEntity(org.apache.commons.httpclient.methods.ByteArrayRequestEntity)

Example 4 with ByteArrayRequestEntity

use of org.apache.commons.httpclient.methods.ByteArrayRequestEntity in project zaproxy by zaproxy.

the class HttpMethodHelper method createRequestMethod.

//  This is the currently in use method.
// may be replaced by the New method - however the New method is not yet fully tested so this is stil used.
public HttpMethod createRequestMethod(HttpRequestHeader header, HttpBody body) throws URIException {
    HttpMethod httpMethod = null;
    String method = header.getMethod();
    URI uri = header.getURI();
    String version = header.getVersion();
    if (method == null || method.trim().length() < 3) {
        throw new URIException("Invalid HTTP method: " + method);
    }
    if (method.equalsIgnoreCase(GET)) {
        //httpMethod = new GetMethod();
        // ZAP: avoid discarding HTTP status code 101 that is used for WebSocket upgrade 
        httpMethod = new ZapGetMethod();
    } else if (method.equalsIgnoreCase(POST)) {
        httpMethod = new ZapPostMethod();
    } else if (method.equalsIgnoreCase(DELETE)) {
        httpMethod = new ZapDeleteMethod();
    } else if (method.equalsIgnoreCase(PUT)) {
        httpMethod = new ZapPutMethod();
    } else if (method.equalsIgnoreCase(HEAD)) {
        httpMethod = new ZapHeadMethod();
    } else if (method.equalsIgnoreCase(OPTIONS)) {
        httpMethod = new ZapOptionsMethod();
    } else if (method.equalsIgnoreCase(TRACE)) {
        httpMethod = new ZapTraceMethod(uri.toString());
    } else {
        httpMethod = new GenericMethod(method);
    }
    try {
        httpMethod.setURI(uri);
    } catch (Exception e1) {
        throw new URIException("Failed to set URI [" + uri + "]: " + e1.getMessage());
    }
    HttpMethodParams httpParams = httpMethod.getParams();
    // default to use HTTP 1.0
    httpParams.setVersion(HttpVersion.HTTP_1_0);
    if (version.equalsIgnoreCase(HttpHeader.HTTP11)) {
        httpParams.setVersion(HttpVersion.HTTP_1_1);
    }
    // set various headers
    int pos = 0;
    // ZAP: changed to always use CRLF, like the HttpHeader
    Pattern pattern = patternCRLF;
    String delimiter = header.getLineDelimiter();
    // ZAP: Shouldn't happen as the HttpHeader always uses CRLF
    if (delimiter.equals(LF)) {
        delimiter = LF;
        pattern = patternLF;
    }
    String msg = header.getHeadersAsString();
    String[] split = pattern.split(msg);
    String token = null;
    String name = null;
    String value = null;
    for (int i = 0; i < split.length; i++) {
        token = split[i];
        if (token.equals("")) {
            continue;
        }
        if ((pos = token.indexOf(":")) < 0) {
            return null;
        }
        name = token.substring(0, pos).trim();
        value = token.substring(pos + 1).trim();
        httpMethod.addRequestHeader(name, value);
    }
    // set body if post method or put method
    if (body != null && body.length() > 0 && (httpMethod instanceof EntityEnclosingMethod)) {
        EntityEnclosingMethod post = (EntityEnclosingMethod) httpMethod;
        //			post.setRequestEntity(new StringRequestEntity(body.toString()));
        post.setRequestEntity(new ByteArrayRequestEntity(body.getBytes()));
    }
    httpMethod.setFollowRedirects(false);
    return httpMethod;
}
Also used : ZapPutMethod(org.zaproxy.zap.network.ZapPutMethod) Pattern(java.util.regex.Pattern) ZapGetMethod(org.zaproxy.zap.ZapGetMethod) ZapTraceMethod(org.zaproxy.zap.network.ZapTraceMethod) EntityEnclosingMethod(org.apache.commons.httpclient.methods.EntityEnclosingMethod) ZapOptionsMethod(org.zaproxy.zap.network.ZapOptionsMethod) ZapHeadMethod(org.zaproxy.zap.network.ZapHeadMethod) HttpMethodParams(org.apache.commons.httpclient.params.HttpMethodParams) URI(org.apache.commons.httpclient.URI) URIException(org.apache.commons.httpclient.URIException) URIException(org.apache.commons.httpclient.URIException) ZapPostMethod(org.zaproxy.zap.network.ZapPostMethod) ZapDeleteMethod(org.zaproxy.zap.network.ZapDeleteMethod) HttpMethod(org.apache.commons.httpclient.HttpMethod) ByteArrayRequestEntity(org.apache.commons.httpclient.methods.ByteArrayRequestEntity)

Example 5 with ByteArrayRequestEntity

use of org.apache.commons.httpclient.methods.ByteArrayRequestEntity in project zm-mailbox by Zimbra.

the class WebDavClient method sendPut.

public HttpInputStream sendPut(String href, byte[] buf, String contentType, String etag, Collection<Pair<String, String>> headers) throws IOException {
    boolean done = false;
    PutMethod put = null;
    while (!done) {
        put = new PutMethod(mBaseUrl + href);
        put.setRequestEntity(new ByteArrayRequestEntity(buf, contentType));
        if (mDebugEnabled && contentType.startsWith("text"))
            ZimbraLog.dav.debug("PUT payload: \n" + new String(buf, "UTF-8"));
        if (etag != null)
            put.setRequestHeader(DavProtocol.HEADER_IF_MATCH, etag);
        if (headers != null)
            for (Pair<String, String> h : headers) put.addRequestHeader(h.getFirst(), h.getSecond());
        executeMethod(put, Depth.zero);
        int ret = put.getStatusCode();
        if (ret == HttpStatus.SC_MOVED_PERMANENTLY || ret == HttpStatus.SC_MOVED_TEMPORARILY) {
            Header newLocation = put.getResponseHeader("Location");
            if (newLocation != null) {
                href = newLocation.getValue();
                ZimbraLog.dav.debug("redirect to new url = " + href);
                put.releaseConnection();
                continue;
            }
        }
        done = true;
    }
    return new HttpInputStream(put);
}
Also used : Header(org.apache.commons.httpclient.Header) PutMethod(org.apache.commons.httpclient.methods.PutMethod) HttpInputStream(com.zimbra.cs.service.UserServlet.HttpInputStream) ByteArrayRequestEntity(org.apache.commons.httpclient.methods.ByteArrayRequestEntity) Pair(com.zimbra.common.util.Pair)

Aggregations

ByteArrayRequestEntity (org.apache.commons.httpclient.methods.ByteArrayRequestEntity)30 HttpClient (org.apache.commons.httpclient.HttpClient)20 PostMethod (org.apache.commons.httpclient.methods.PostMethod)11 Account (com.zimbra.cs.account.Account)9 PutMethod (org.apache.commons.httpclient.methods.PutMethod)8 Test (org.junit.Test)8 Header (org.apache.commons.httpclient.Header)5 RequestEntity (org.apache.commons.httpclient.methods.RequestEntity)5 Document (org.w3c.dom.Document)5 Element (com.zimbra.common.soap.Element)4 GetMethod (org.apache.commons.httpclient.methods.GetMethod)4 ZMailbox (com.zimbra.client.ZMailbox)3 HttpMethod (org.apache.commons.httpclient.HttpMethod)3 EntityEnclosingMethod (org.apache.commons.httpclient.methods.EntityEnclosingMethod)3 SearchRequest (com.zimbra.soap.mail.message.SearchRequest)2 SearchResponse (com.zimbra.soap.mail.message.SearchResponse)2 SearchHit (com.zimbra.soap.type.SearchHit)2 ByteArrayOutputStream (java.io.ByteArrayOutputStream)2 IOException (java.io.IOException)2 InputStream (java.io.InputStream)2