Search in sources :

Example 11 with HttpMethodParams

use of org.apache.commons.httpclient.params.HttpMethodParams in project camel by apache.

the class HttpProducer method process.

public void process(Exchange exchange) throws Exception {
    // if we bridge endpoint then we need to skip matching headers with the HTTP_QUERY to avoid sending
    // duplicated headers to the receiver, so use this skipRequestHeaders as the list of headers to skip
    Map<String, Object> skipRequestHeaders = null;
    if (getEndpoint().isBridgeEndpoint()) {
        exchange.setProperty(Exchange.SKIP_GZIP_ENCODING, Boolean.TRUE);
        String queryString = exchange.getIn().getHeader(Exchange.HTTP_QUERY, String.class);
        if (queryString != null) {
            skipRequestHeaders = URISupport.parseQuery(queryString, false, true);
        }
        // Need to remove the Host key as it should be not used 
        exchange.getIn().getHeaders().remove("host");
    }
    HttpMethod method = createMethod(exchange);
    Message in = exchange.getIn();
    String httpProtocolVersion = in.getHeader(Exchange.HTTP_PROTOCOL_VERSION, String.class);
    if (httpProtocolVersion != null) {
        // set the HTTP protocol version
        HttpMethodParams params = method.getParams();
        params.setVersion(HttpVersion.parse(httpProtocolVersion));
    }
    HeaderFilterStrategy strategy = getEndpoint().getHeaderFilterStrategy();
    // propagate headers as HTTP headers
    for (Map.Entry<String, Object> entry : in.getHeaders().entrySet()) {
        String key = entry.getKey();
        Object headerValue = in.getHeader(key);
        if (headerValue != null) {
            // use an iterator as there can be multiple values. (must not use a delimiter, and allow empty values)
            final Iterator<?> it = ObjectHelper.createIterator(headerValue, null, true);
            // the value to add as request header
            final List<String> values = new ArrayList<String>();
            // should be combined into a single value
            while (it.hasNext()) {
                String value = exchange.getContext().getTypeConverter().convertTo(String.class, it.next());
                // as then we would duplicate headers on both the endpoint uri, and in HTTP headers as well
                if (skipRequestHeaders != null && skipRequestHeaders.containsKey(key)) {
                    continue;
                }
                if (value != null && strategy != null && !strategy.applyFilterToCamelHeaders(key, value, exchange)) {
                    values.add(value);
                }
            }
            // add the value(s) as a http request header
            if (values.size() > 0) {
                // use the default toString of a ArrayList to create in the form [xxx, yyy]
                // if multi valued, for a single value, then just output the value as is
                String s = values.size() > 1 ? values.toString() : values.get(0);
                method.addRequestHeader(key, s);
            }
        }
    }
    if (getEndpoint().getCookieHandler() != null) {
        // disable the per endpoint cookie handling
        method.getParams().setCookiePolicy(CookiePolicy.IGNORE_COOKIES);
        Map<String, List<String>> cookieHeaders = getEndpoint().getCookieHandler().loadCookies(exchange, new URI(method.getURI().getEscapedURI()));
        for (Map.Entry<String, List<String>> entry : cookieHeaders.entrySet()) {
            String key = entry.getKey();
            if (entry.getValue().size() > 0) {
                // use the default toString of a ArrayList to create in the form [xxx, yyy]
                // if multi valued, for a single value, then just output the value as is
                String s = entry.getValue().size() > 1 ? entry.getValue().toString() : entry.getValue().get(0);
                method.addRequestHeader(key, s);
            }
        }
    }
    if (getEndpoint().isConnectionClose()) {
        method.addRequestHeader("Connection", "close");
    }
    // lets store the result in the output message.
    try {
        if (LOG.isDebugEnabled()) {
            LOG.debug("Executing http {} method: {}", method.getName(), method.getURI().toString());
        }
        int responseCode = executeMethod(method);
        LOG.debug("Http responseCode: {}", responseCode);
        if (!throwException) {
            // if we do not use failed exception then populate response for all response codes
            populateResponse(exchange, method, in, strategy, responseCode);
        } else {
            boolean ok = HttpHelper.isStatusCodeOk(responseCode, getEndpoint().getOkStatusCodeRange());
            if (ok) {
                // only populate response for OK response
                populateResponse(exchange, method, in, strategy, responseCode);
            } else {
                // operation failed so populate exception to throw
                throw populateHttpOperationFailedException(exchange, method, responseCode);
            }
        }
    } finally {
        method.releaseConnection();
    }
}
Also used : Message(org.apache.camel.Message) ArrayList(java.util.ArrayList) HttpProtocolHeaderFilterStrategy(org.apache.camel.http.common.HttpProtocolHeaderFilterStrategy) HeaderFilterStrategy(org.apache.camel.spi.HeaderFilterStrategy) HttpMethodParams(org.apache.commons.httpclient.params.HttpMethodParams) URI(java.net.URI) ArrayList(java.util.ArrayList) List(java.util.List) HashMap(java.util.HashMap) Map(java.util.Map) HttpMethod(org.apache.commons.httpclient.HttpMethod)

Example 12 with HttpMethodParams

use of org.apache.commons.httpclient.params.HttpMethodParams in project camel by apache.

the class MultiPartFormTest method createMultipartRequestEntity.

private RequestEntity createMultipartRequestEntity() throws Exception {
    File file = new File("src/main/resources/META-INF/NOTICE.txt");
    Part[] parts = { new StringPart("comment", "A binary file of some kind"), new FilePart(file.getName(), file) };
    return new MultipartRequestEntity(parts, new HttpMethodParams());
}
Also used : StringPart(org.apache.commons.httpclient.methods.multipart.StringPart) FilePart(org.apache.commons.httpclient.methods.multipart.FilePart) Part(org.apache.commons.httpclient.methods.multipart.Part) StringPart(org.apache.commons.httpclient.methods.multipart.StringPart) HttpMethodParams(org.apache.commons.httpclient.params.HttpMethodParams) File(java.io.File) MultipartRequestEntity(org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity) FilePart(org.apache.commons.httpclient.methods.multipart.FilePart)

Example 13 with HttpMethodParams

use of org.apache.commons.httpclient.params.HttpMethodParams in project hadoop by apache.

the class SwiftRestClient method perform.

/**
   * Performs the HTTP request, validates the response code and returns
   * the received data. HTTP Status codes are converted into exceptions.
   * @param reason why is this operation taking place. Used for statistics
   * @param uri URI to source
   * @param processor HttpMethodProcessor
   * @param <M> method
   * @param <R> result type
   * @return result of HTTP request
   * @throws IOException IO problems
   * @throws SwiftBadRequestException the status code indicated "Bad request"
   * @throws SwiftInvalidResponseException the status code is out of range
   * for the action (excluding 404 responses)
   * @throws SwiftInternalStateException the internal state of this client
   * is invalid
   * @throws FileNotFoundException a 404 response was returned
   */
private <M extends HttpMethod, R> R perform(String reason, URI uri, HttpMethodProcessor<M, R> processor) throws IOException, SwiftBadRequestException, SwiftInternalStateException, SwiftInvalidResponseException, FileNotFoundException {
    checkNotNull(uri);
    checkNotNull(processor);
    final M method = processor.createMethod(uri.toString());
    //retry policy
    HttpMethodParams methodParams = method.getParams();
    methodParams.setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(retryCount, false));
    methodParams.setIntParameter(HttpConnectionParams.CONNECTION_TIMEOUT, connectTimeout);
    methodParams.setSoTimeout(socketTimeout);
    method.addRequestHeader(HEADER_USER_AGENT, SWIFT_USER_AGENT);
    Duration duration = new Duration();
    boolean success = false;
    try {
        int statusCode = 0;
        try {
            statusCode = exec(method);
        } catch (IOException e) {
            //rethrow with extra diagnostics and wiki links
            throw ExceptionDiags.wrapException(uri.toString(), method.getName(), e);
        }
        //look at the response and see if it was valid or not.
        //Valid is more than a simple 200; even 404 "not found" is considered
        //valid -which it is for many methods.
        //validate the allowed status code for this operation
        int[] allowedStatusCodes = processor.getAllowedStatusCodes();
        boolean validResponse = isStatusCodeExpected(statusCode, allowedStatusCodes);
        if (!validResponse) {
            IOException ioe = buildException(uri, method, statusCode);
            throw ioe;
        }
        R r = processor.extractResult(method);
        success = true;
        return r;
    } catch (IOException e) {
        //release the connection -always
        method.releaseConnection();
        throw e;
    } finally {
        duration.finished();
        durationStats.add(method.getName() + " " + reason, duration, success);
    }
}
Also used : DefaultHttpMethodRetryHandler(org.apache.commons.httpclient.DefaultHttpMethodRetryHandler) Duration(org.apache.hadoop.fs.swift.util.Duration) IOException(java.io.IOException) HttpMethodParams(org.apache.commons.httpclient.params.HttpMethodParams) Endpoint(org.apache.hadoop.fs.swift.auth.entities.Endpoint)

Example 14 with HttpMethodParams

use of org.apache.commons.httpclient.params.HttpMethodParams in project twitter-2-weibo by rjyo.

the class HttpClient method post.

public Response post(String url, PostParameter[] params, Boolean WithTokenHeader) throws WeiboException {
    log("Request:");
    log("POST" + url);
    PostMethod postMethod = new PostMethod(url);
    for (int i = 0; i < params.length; i++) {
        postMethod.addParameter(params[i].getName(), params[i].getValue());
    }
    HttpMethodParams param = postMethod.getParams();
    param.setContentCharset("UTF-8");
    if (WithTokenHeader) {
        return httpRequest(postMethod);
    } else {
        return httpRequest(postMethod, WithTokenHeader);
    }
}
Also used : PostMethod(org.apache.commons.httpclient.methods.PostMethod) HttpMethodParams(org.apache.commons.httpclient.params.HttpMethodParams)

Example 15 with HttpMethodParams

use of org.apache.commons.httpclient.params.HttpMethodParams in project zaproxy by zaproxy.

the class HttpMethodHelper method createRequestMethodNew.

// Not used - all abstract using Generic method but GET cannot be used.
public HttpMethod createRequestMethodNew(HttpRequestHeader header, HttpBody body) throws URIException {
    HttpMethod httpMethod = null;
    String method = header.getMethod();
    URI uri = header.getURI();
    String version = header.getVersion();
    httpMethod = new GenericMethod(method);
    httpMethod.setURI(uri);
    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: FindBugs fix - always initialise pattern
    Pattern pattern = patternCRLF;
    String delimiter = CRLF;
    String msg = header.getHeadersAsString();
    if ((pos = msg.indexOf(CRLF)) < 0) {
        if ((pos = msg.indexOf(LF)) < 0) {
            delimiter = LF;
            pattern = patternLF;
        }
    } else {
        delimiter = CRLF;
        pattern = patternCRLF;
    }
    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) {
        EntityEnclosingMethod generic = (EntityEnclosingMethod) httpMethod;
        //			generic.setRequestEntity(new StringRequestEntity(body.toString()));
        generic.setRequestEntity(new ByteArrayRequestEntity(body.getBytes()));
    }
    httpMethod.setFollowRedirects(false);
    return httpMethod;
}
Also used : Pattern(java.util.regex.Pattern) EntityEnclosingMethod(org.apache.commons.httpclient.methods.EntityEnclosingMethod) HttpMethodParams(org.apache.commons.httpclient.params.HttpMethodParams) URI(org.apache.commons.httpclient.URI) HttpMethod(org.apache.commons.httpclient.HttpMethod) ByteArrayRequestEntity(org.apache.commons.httpclient.methods.ByteArrayRequestEntity)

Aggregations

HttpMethodParams (org.apache.commons.httpclient.params.HttpMethodParams)16 IOException (java.io.IOException)5 MultipartRequestEntity (org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity)5 HttpMethod (org.apache.commons.httpclient.HttpMethod)4 PostMethod (org.apache.commons.httpclient.methods.PostMethod)4 Part (org.apache.commons.httpclient.methods.multipart.Part)4 HttpClient (org.apache.commons.httpclient.HttpClient)3 UsernamePasswordCredentials (org.apache.commons.httpclient.UsernamePasswordCredentials)3 EntityEnclosingMethod (org.apache.commons.httpclient.methods.EntityEnclosingMethod)3 GetMethod (org.apache.commons.httpclient.methods.GetMethod)3 FilePart (org.apache.commons.httpclient.methods.multipart.FilePart)3 StringPart (org.apache.commons.httpclient.methods.multipart.StringPart)3 BufferedInputStream (java.io.BufferedInputStream)2 File (java.io.File)2 HashMap (java.util.HashMap)2 Map (java.util.Map)2 Pattern (java.util.regex.Pattern)2 DefaultHttpMethodRetryHandler (org.apache.commons.httpclient.DefaultHttpMethodRetryHandler)2 Header (org.apache.commons.httpclient.Header)2 HttpException (org.apache.commons.httpclient.HttpException)2