Example usage for org.apache.commons.httpclient HttpMethod setRequestHeader

List of usage examples for org.apache.commons.httpclient HttpMethod setRequestHeader

Introduction

In this page you can find the example usage for org.apache.commons.httpclient HttpMethod setRequestHeader.

Prototype

public abstract void setRequestHeader(Header paramHeader);

Source Link

Usage

From source file:org.apache.ode.axis2.httpbinding.HttpMethodConverter.java

/**
 * First go through the list of default headers set in the method params. This param is then remove to avoid interference with HttpClient.
 * Actually the default headers should be overriden by any headers set from the process.
 * Not to mention that, for a given header, HttpClient do not overwrite any previous values but simply append the default value.<br/>
 *  See {@link see org.apache.commons.httpclient.params.HostParams.DEFAULT_HEADERS}
 * <p/>//  w  w w.  jav  a2 s . c o  m
 * Then go through the list of message headers and set them if empty.
 * <p/>
 * Finally go through the list of {@linkplain Namespaces.ODE_HTTP_EXTENSION_NS}{@code :header} elements included in the input binding.
 * For each of them, set the HTTP Request Header with the static value defined by the attribute {@linkplain Namespaces.ODE_HTTP_EXTENSION_NS}{@code :value},
 * or the part value mentioned in the attribute {@linkplain Namespaces.ODE_HTTP_EXTENSION_NS}{@code :part}.
 * <p/>
 * Finally, set the 'Accept' header if the output content type of the operation exists.
 * <p/>
 * Notice that the last header value overrides any values set previoulsy. Meaning that message headers might get overriden by parts bound to headers.
 *
 */
public void setHttpRequestHeaders(HttpMethod method, BindingOperation opBinding,
        Map<String, Element> partValues, Map<String, Node> headers, HttpParams params) {
    BindingInput inputBinding = opBinding.getBindingInput();
    Message inputMessage = opBinding.getOperation().getInput().getMessage();

    // Do not let HttpClient manage the default headers
    // Actually the default headers should be overriden by any headers set from the process.
    // (Not to mention that, for a given header, HttpClient do not overwrite any previous values but simply append the default value)
    Collection defaultHeaders = (Collection) params.getParameter(HostParams.DEFAULT_HEADERS);
    if (defaultHeaders != null) {
        Iterator i = defaultHeaders.iterator();
        while (i.hasNext()) {
            method.setRequestHeader((Header) i.next());
        }
    }

    // process message headers
    for (Iterator<Map.Entry<String, Node>> iterator = headers.entrySet().iterator(); iterator.hasNext();) {
        Map.Entry<String, Node> e = iterator.next();
        String headerName = e.getKey();
        Node headerNode = e.getValue();
        String headerValue = DOMUtils.domToString(headerNode);
        method.setRequestHeader(headerName, HttpHelper.replaceCRLFwithLWS(headerValue));
    }

    // process parts that are bound to message parts
    Collection<UnknownExtensibilityElement> headerBindings = WsdlUtils
            .getHttpHeaders(inputBinding.getExtensibilityElements());
    for (Iterator<UnknownExtensibilityElement> iterator = headerBindings.iterator(); iterator.hasNext();) {
        Element binding = iterator.next().getElement();
        String headerName = binding.getAttribute("name");
        String partName = binding.getAttribute("part");
        String value = binding.getAttribute("value");

        /* Header binding may use a part or a static value */
        String headerValue;
        if (StringUtils.isNotEmpty(partName)) {
            // 'part' attribute is used
            // get the part to be put in the header
            Part part = inputMessage.getPart(partName);
            Element partWrapper = partValues.get(part.getName());
            if (DOMUtils.isEmptyElement(partWrapper)) {
                headerValue = "";
            } else {
                /*
                The expected part value could be a simple type
                or an element of a simple type.
                So if a element is there, take its text content
                else take the text content of the part element itself
                */
                Element childElement = DOMUtils.getFirstChildElement(partWrapper);
                if (childElement != null) {
                    if (DOMUtils.getFirstChildElement(childElement) != null) {
                        String errMsg = "Complex types are not supported. Header Parts must be simple types or elements of a simple type.";
                        if (log.isErrorEnabled())
                            log.error(errMsg);
                        throw new RuntimeException(errMsg);
                    } else {
                        headerValue = DOMUtils.getTextContent(childElement);
                    }
                } else {
                    headerValue = DOMUtils.getTextContent(partWrapper);
                }
            }
        } else if (StringUtils.isNotEmpty(value)) {
            // 'value' attribute is used, this header is a static value
            headerValue = value;
        } else {
            String errMsg = "Invalid binding: missing attribute! Expecting "
                    + new QName(Namespaces.ODE_HTTP_EXTENSION_NS, "part") + " or "
                    + new QName(Namespaces.ODE_HTTP_EXTENSION_NS, "value");
            if (log.isErrorEnabled())
                log.error(errMsg);
            throw new RuntimeException(errMsg);
        }
        // do not set the header isf the value is empty
        if (StringUtils.isNotEmpty(headerValue))
            method.setRequestHeader(headerName, HttpHelper.replaceCRLFwithLWS(headerValue));
    }

    MIMEContent outputContent = WsdlUtils
            .getMimeContent(opBinding.getBindingOutput().getExtensibilityElements());
    // set Accept header if output content type is set
    if (outputContent != null) {
        method.setRequestHeader("Accept", outputContent.getType());
    }

}

From source file:org.apache.solr.client.solrj.impl.CommonsHttpSolrServer.java

public NamedList<Object> request(final SolrRequest request, ResponseParser processor)
        throws SolrServerException, IOException {
    HttpMethod method = null;
    InputStream is = null;//w w  w . j  a va2  s  . com
    SolrParams params = request.getParams();
    Collection<ContentStream> streams = requestWriter.getContentStreams(request);
    String path = requestWriter.getPath(request);
    if (path == null || !path.startsWith("/")) {
        path = "/select";
    }

    ResponseParser parser = request.getResponseParser();
    if (parser == null) {
        parser = _parser;
    }

    // The parser 'wt=' and 'version=' params are used instead of the original params
    ModifiableSolrParams wparams = new ModifiableSolrParams();
    wparams.set(CommonParams.WT, parser.getWriterType());
    wparams.set(CommonParams.VERSION, parser.getVersion());
    if (params == null) {
        params = wparams;
    } else {
        params = new DefaultSolrParams(wparams, params);
    }

    if (_invariantParams != null) {
        params = new DefaultSolrParams(_invariantParams, params);
    }

    int tries = _maxRetries + 1;
    try {
        while (tries-- > 0) {
            // Note: since we aren't do intermittent time keeping
            // ourselves, the potential non-timeout latency could be as
            // much as tries-times (plus scheduling effects) the given
            // timeAllowed.
            try {
                if (SolrRequest.METHOD.GET == request.getMethod()) {
                    if (streams != null) {
                        throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, "GET can't send streams!");
                    }
                    method = new GetMethod(_baseURL + path + ClientUtils.toQueryString(params, false));
                } else if (SolrRequest.METHOD.POST == request.getMethod()) {

                    String url = _baseURL + path;
                    boolean isMultipart = (streams != null && streams.size() > 1);

                    if (streams == null || isMultipart) {
                        PostMethod post = new PostMethod(url);
                        post.getParams().setContentCharset("UTF-8");
                        if (!this.useMultiPartPost && !isMultipart) {
                            post.addRequestHeader("Content-Type",
                                    "application/x-www-form-urlencoded; charset=UTF-8");
                        }

                        List<Part> parts = new LinkedList<Part>();
                        Iterator<String> iter = params.getParameterNamesIterator();
                        while (iter.hasNext()) {
                            String p = iter.next();
                            String[] vals = params.getParams(p);
                            if (vals != null) {
                                for (String v : vals) {
                                    if (this.useMultiPartPost || isMultipart) {
                                        parts.add(new StringPart(p, v, "UTF-8"));
                                    } else {
                                        post.addParameter(p, v);
                                    }
                                }
                            }
                        }

                        if (isMultipart) {
                            int i = 0;
                            for (ContentStream content : streams) {
                                final ContentStream c = content;

                                String charSet = null;
                                PartSource source = new PartSource() {
                                    public long getLength() {
                                        return c.getSize();
                                    }

                                    public String getFileName() {
                                        return c.getName();
                                    }

                                    public InputStream createInputStream() throws IOException {
                                        return c.getStream();
                                    }
                                };

                                parts.add(new FilePart(c.getName(), source, c.getContentType(), charSet));
                            }
                        }
                        if (parts.size() > 0) {
                            post.setRequestEntity(new MultipartRequestEntity(
                                    parts.toArray(new Part[parts.size()]), post.getParams()));
                        }

                        method = post;
                    }
                    // It is has one stream, it is the post body, put the params in the URL
                    else {
                        String pstr = ClientUtils.toQueryString(params, false);
                        PostMethod post = new PostMethod(url + pstr);
                        //              post.setRequestHeader("connection", "close");

                        // Single stream as body
                        // Using a loop just to get the first one
                        final ContentStream[] contentStream = new ContentStream[1];
                        for (ContentStream content : streams) {
                            contentStream[0] = content;
                            break;
                        }
                        if (contentStream[0] instanceof RequestWriter.LazyContentStream) {
                            post.setRequestEntity(new RequestEntity() {
                                public long getContentLength() {
                                    return -1;
                                }

                                public String getContentType() {
                                    return contentStream[0].getContentType();
                                }

                                public boolean isRepeatable() {
                                    return false;
                                }

                                public void writeRequest(OutputStream outputStream) throws IOException {
                                    ((RequestWriter.LazyContentStream) contentStream[0]).writeTo(outputStream);
                                }
                            });

                        } else {
                            is = contentStream[0].getStream();
                            post.setRequestEntity(
                                    new InputStreamRequestEntity(is, contentStream[0].getContentType()));
                        }
                        method = post;
                    }
                } else {
                    throw new SolrServerException("Unsupported method: " + request.getMethod());
                }
            } catch (NoHttpResponseException r) {
                // This is generally safe to retry on
                method.releaseConnection();
                method = null;
                if (is != null) {
                    is.close();
                }
                // If out of tries then just rethrow (as normal error).
                if ((tries < 1)) {
                    throw r;
                }
                //log.warn( "Caught: " + r + ". Retrying..." );
            }
        }
    } catch (IOException ex) {
        log.error("####request####", ex);
        throw new SolrServerException("error reading streams", ex);
    }

    method.setFollowRedirects(_followRedirects);
    method.addRequestHeader("User-Agent", AGENT);
    if (_allowCompression) {
        method.setRequestHeader(new Header("Accept-Encoding", "gzip,deflate"));
    }
    //    method.setRequestHeader("connection", "close");

    try {
        // Execute the method.
        //System.out.println( "EXECUTE:"+method.getURI() );

        int statusCode = _httpClient.executeMethod(method);
        if (statusCode != HttpStatus.SC_OK) {
            StringBuilder msg = new StringBuilder();
            msg.append(method.getStatusLine().getReasonPhrase());
            msg.append("\n\n");
            msg.append(method.getStatusText());
            msg.append("\n\n");
            msg.append("request: " + method.getURI());
            throw new SolrException(statusCode, java.net.URLDecoder.decode(msg.toString(), "UTF-8"));
        }

        // Read the contents
        String charset = "UTF-8";
        if (method instanceof HttpMethodBase) {
            charset = ((HttpMethodBase) method).getResponseCharSet();
        }
        InputStream respBody = method.getResponseBodyAsStream();
        // Jakarta Commons HTTPClient doesn't handle any
        // compression natively.  Handle gzip or deflate
        // here if applicable.
        if (_allowCompression) {
            Header contentEncodingHeader = method.getResponseHeader("Content-Encoding");
            if (contentEncodingHeader != null) {
                String contentEncoding = contentEncodingHeader.getValue();
                if (contentEncoding.contains("gzip")) {
                    //log.debug( "wrapping response in GZIPInputStream" );
                    respBody = new GZIPInputStream(respBody);
                } else if (contentEncoding.contains("deflate")) {
                    //log.debug( "wrapping response in InflaterInputStream" );
                    respBody = new InflaterInputStream(respBody);
                }
            } else {
                Header contentTypeHeader = method.getResponseHeader("Content-Type");
                if (contentTypeHeader != null) {
                    String contentType = contentTypeHeader.getValue();
                    if (contentType != null) {
                        if (contentType.startsWith("application/x-gzip-compressed")) {
                            //log.debug( "wrapping response in GZIPInputStream" );
                            respBody = new GZIPInputStream(respBody);
                        } else if (contentType.startsWith("application/x-deflate")) {
                            //log.debug( "wrapping response in InflaterInputStream" );
                            respBody = new InflaterInputStream(respBody);
                        }
                    }
                }
            }
        }
        return processor.processResponse(respBody, charset);
    } catch (HttpException e) {
        throw new SolrServerException(e);
    } catch (IOException e) {
        throw new SolrServerException(e);
    } finally {
        method.releaseConnection();
        if (is != null) {
            is.close();
        }
    }
}

From source file:org.chiba.xml.xforms.connector.http.AbstractHTTPConnector.java

/**
 * Performs a HTTP GET request.//  ww w  .  j ava 2s. c  om
 *
 * @param uri the request uri.
 * @throws XFormsException if any error occurred during the request.
 */
protected void get(String uri) throws XFormsException {
    try {
        HttpMethod httpMethod = new GetMethod(uri);
        httpMethod.setRequestHeader(new Header("User-Agent", ChibaBean.getAppInfo()));

        execute(httpMethod);
    } catch (Exception e) {
        throw new XFormsException(e);
    }
}

From source file:org.codeartisans.proxilet.Proxilet.java

/**
 * Retreives all of the headers from the servlet request and sets them on the proxy request.
 *
 * @param httpServletRequest        The request object representing the client's request to the servlet engine
 * @param httpMethodProxyRequest    The request that we are about to send to the proxy host
 *//*from  www. jav a2s .c o  m*/
@SuppressWarnings("unchecked")
private void setProxyRequestHeaders(HttpServletRequest httpServletRequest, HttpMethod httpMethodProxyRequest) {
    // Get an Enumeration of all of the header names sent by the client
    Enumeration<String> enumerationOfHeaderNames = httpServletRequest.getHeaderNames();
    while (enumerationOfHeaderNames.hasMoreElements()) {
        String stringHeaderName = enumerationOfHeaderNames.nextElement();
        if (stringHeaderName.equalsIgnoreCase(HEADER_CONTENT_LENGTH)) {
            continue;
        }
        // As per the Java Servlet API 2.5 documentation:
        // Some headers, such as Accept-Language can be sent by clients
        // as several headers each with a different value rather than
        // sending the header as a comma separated list.
        // Thus, we get an Enumeration of the header values sent by the client
        Enumeration<String> enumerationOfHeaderValues = httpServletRequest.getHeaders(stringHeaderName);
        while (enumerationOfHeaderValues.hasMoreElements()) {
            String stringHeaderValue = enumerationOfHeaderValues.nextElement();
            // In case the proxy host is running multiple virtual servers,
            // rewrite the Host header to ensure that we get content from
            // the correct virtual server
            if (stringHeaderName.equalsIgnoreCase(HEADER_HOST)) {
                stringHeaderValue = getProxyHostAndPort();
            }
            Header header = new Header(stringHeaderName, stringHeaderValue);
            // Set the same header on the proxy request
            httpMethodProxyRequest.setRequestHeader(header);
        }
    }
}

From source file:org.infoscoop.request.filter.ProxyFilterContainer.java

public final int invoke(HttpClient client, HttpMethod method, ProxyRequest request) throws Exception {
    int preStatus = prepareInvoke(client, method, request);
    switch (preStatus) {
    case 0:/*from  w w w. ja v  a 2s.  com*/
        break;
    case EXECUTE_POST_STATUS:
        doFilterChain(request, request.getResponseBody());
    default:
        return preStatus;
    }
    // copy headers sent target server
    List ignoreHeaderNames = request.getIgnoreHeaders();
    List allowedHeaderNames = request.getAllowedHeaders();
    boolean allowAllHeader = false;

    Proxy proxy = request.getProxy();
    if (proxy != null) {
        allowAllHeader = proxy.isAllowAllHeader();
        if (!allowAllHeader)
            allowedHeaderNames.addAll(proxy.getAllowedHeaders());
    }

    AuthenticatorUtil.doAuthentication(client, method, request);

    StringBuffer headersSb = new StringBuffer();
    for (String name : request.getRequestHeaders().keySet()) {

        String value = request.getRequestHeader(name);
        String lowname = name.toLowerCase();

        if (!allowAllHeader && !allowedHeaderNames.contains(lowname))
            continue;

        if (ignoreHeaderNames.contains(lowname))
            continue;

        if ("cookie".equalsIgnoreCase(name)) {
            if (proxy.getSendingCookies() != null) {
                value = RequestUtil.removeCookieParam(value, proxy.getSendingCookies());
            }
        }

        if ("if-modified-since".equalsIgnoreCase(name) && "Thu, 01 Jun 1970 00:00:00 GMT".equals(value))
            continue;

        method.addRequestHeader(new Header(name, value));
        headersSb.append(name + "=" + value + ",  ");
    }

    int cacheStatus = getCache(client, method, request);
    if (cacheStatus != 0)
        return cacheStatus;

    if (log.isInfoEnabled())
        log.info("RequestHeader: " + headersSb);

    // execute http method and process redirect
    method.setFollowRedirects(false);

    client.executeMethod(method);

    int statusCode = method.getStatusCode();

    for (int i = 0; statusCode == HttpStatus.SC_MOVED_TEMPORARILY
            || statusCode == HttpStatus.SC_MOVED_PERMANENTLY || statusCode == HttpStatus.SC_SEE_OTHER
            || statusCode == HttpStatus.SC_TEMPORARY_REDIRECT; i++) {

        // connection release
        method.releaseConnection();

        if (i == 5) {
            log.error("The circular redirect is limited by five times.");
            return 500;
        }

        Header location = method.getResponseHeader("Location");
        String redirectUrl = location.getValue();

        // According to 2,068 1.1 rfc http spec, we cannot appoint the relative URL,
        // but microsoft.com gives back the relative URL.
        if (redirectUrl.startsWith("/")) {
            URI baseURI = method.getURI();
            baseURI.setPath(redirectUrl);

            redirectUrl = baseURI.toString();
        }

        //method.setURI(new URI(redirectUrl, false));
        Header[] headers = method.getRequestHeaders();
        method = new GetMethod(redirectUrl);
        for (int j = 0; j < headers.length; j++) {
            String headerName = headers[j].getName();
            if (!headerName.equalsIgnoreCase("content-length") && !headerName.equalsIgnoreCase("authorization"))
                method.setRequestHeader(headers[j]);
        }
        AuthenticatorUtil.doAuthentication(client, method, request);
        method.setRequestHeader("authorization", request.getRequestHeader("Authorization"));
        method.setFollowRedirects(false);
        client.executeMethod(method);
        statusCode = method.getStatusCode();
        request.setRedirectURL(redirectUrl);

        if (log.isInfoEnabled())
            log.info("Redirect " + request.getTargetURL() + " to " + location + ".");
    }

    // copy response headers to proxyReqeust
    Header[] headers = method.getResponseHeaders();
    for (int i = 0; i < headers.length; i++) {
        request.putResponseHeader(headers[i].getName(), headers[i].getValue());
    }

    if (log.isInfoEnabled())
        log.info("Original Status:" + statusCode);

    // check response code
    if (statusCode == HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED) {
        log.error("Proxy Authentication Required. Confirm ajax proxy setting.");
        throw new Exception(
                "Http Status 407, Proxy Authentication Required. Please contuct System Administrator.");
    }
    if (statusCode == HttpStatus.SC_NOT_MODIFIED || statusCode == HttpStatus.SC_RESET_CONTENT) {
        return statusCode;
    } else if (statusCode < 200 || statusCode >= 300) {
        request.setResponseBody(method.getResponseBodyAsStream());
        return statusCode;
    }

    // process response body
    InputStream responseStream = null;
    if (statusCode != HttpStatus.SC_NO_CONTENT) {
        if (request.allowUserPublicCache()) {
            byte[] responseBody = method.getResponseBody();

            Map<String, List<String>> responseHeaders = request.getResponseHeaders();
            if (request.getRedirectURL() != null)
                responseHeaders.put("X-IS-REDIRECTED-FROM",
                        Arrays.asList(new String[] { request.getRedirectURL() }));
            if (method instanceof GetMethod) {
                putCache(request.getOriginalURL(), new ByteArrayInputStream(responseBody), responseHeaders);
            }

            responseStream = new ByteArrayInputStream(responseBody);
        } else {
            responseStream = method.getResponseBodyAsStream();
        }
    }
    doFilterChain(request, responseStream);

    return statusCode != HttpStatus.SC_NO_CONTENT ? method.getStatusCode() : 200;
}

From source file:org.j2free.http.HttpCallable.java

public HttpCallResult call() throws IOException {
    HttpMethod method;

    if (task.method == HttpCallTask.Method.GET)
        method = new GetMethod(task.toString());
    else {//from  w w w .  j a  va  2  s  . co  m
        method = new PostMethod(task.url);

        String postBody = task.getExplicitPostBody();
        if (postBody != null) {

            ((PostMethod) method).setRequestEntity(new StringRequestEntity(postBody, "text/xml", null));
        } else {
            List<KeyValuePair<String, String>> params = task.getQueryParams();
            NameValuePair[] data = new NameValuePair[params.size()];

            int i = 0;
            for (KeyValuePair<String, String> param : params) {
                data[i] = new NameValuePair(param.key, param.value);
                i++;
            }

            ((PostMethod) method).setRequestBody(data);
        }
    }

    for (Header header : task.getRequestHeaders()) {
        method.setRequestHeader(header);
    }

    method.setFollowRedirects(task.followRedirects);

    try {
        if (log.isDebugEnabled())
            log.debug("Making HTTP call [url=" + task.toString() + "]");

        client.executeMethod(method);

        if (log.isDebugEnabled())
            log.debug("Call returned [status=" + method.getStatusCode() + "]");

        return new HttpCallResult(method);
    } finally {
        // ALWAYS release the connection!!!
        method.releaseConnection();
    }
}

From source file:org.jboss.orion.openshift.server.proxy.JsonProxyServlet.java

/**
 * Retrieves all of the headers from the servlet request and sets them on
 * the proxy request//ww w  . j a va 2s.c  o  m
 *
 * @param proxyDetails
 * @param httpServletRequest     The request object representing the client's
 *                               request to the servlet engine
 * @param httpMethodProxyRequest The request that we are about to send to
 */
private void setProxyRequestHeaders(ProxyDetails proxyDetails, HttpServletRequest httpServletRequest,
        HttpMethod httpMethodProxyRequest) {
    // Get an Enumeration of all of the header names sent by the client
    Enumeration<?> enumerationOfHeaderNames = httpServletRequest.getHeaderNames();
    while (enumerationOfHeaderNames.hasMoreElements()) {
        String stringHeaderName = (String) enumerationOfHeaderNames.nextElement();

        if (stringHeaderName.equalsIgnoreCase(STRING_CONTENT_LENGTH_HEADER_NAME)
                || ProxySupport.isHopByHopHeader(stringHeaderName))
            continue;
        // As per the Java Servlet API 2.5 documentation:
        //      Some headers, such as Accept-Language can be sent by clients
        //      as several headers each with a different value rather than
        //      sending the header as a comma separated list.
        // Thus, we get an Enumeration of the header values sent by the client
        Enumeration<?> enumerationOfHeaderValues = httpServletRequest.getHeaders(stringHeaderName);
        while (enumerationOfHeaderValues.hasMoreElements()) {
            String stringHeaderValue = (String) enumerationOfHeaderValues.nextElement();
            // In case the proxy host is running multiple virtual servers,
            // rewrite the Host header to ensure that we get content from
            // the correct virtual server
            if (stringHeaderName.equalsIgnoreCase(STRING_HOST_HEADER_NAME)) {
                stringHeaderValue = proxyDetails.getProxyHostAndPort();
            }
            Header header = new Header(stringHeaderName, stringHeaderValue);
            // Set the same header on the proxy request
            httpMethodProxyRequest.setRequestHeader(header);
        }
        httpMethodProxyRequest.setRequestHeader("Accept-Encoding", "");
    }
}

From source file:org.mozilla.zest.impl.ZestBasicRunner.java

private ZestResponse send(HttpClient httpclient, ZestRequest req) throws IOException {
    HttpMethod method;
    URI uri = new URI(req.getUrl().toString(), false);

    switch (req.getMethod()) {
    case "GET":
        method = new GetMethod(uri.toString());
        // Can only redirect on GETs
        method.setFollowRedirects(req.isFollowRedirects());
        break;// w  w w.  j av a 2 s  .co m
    case "POST":
        method = new PostMethod(uri.toString());
        break;
    case "OPTIONS":
        method = new OptionsMethod(uri.toString());
        break;
    case "HEAD":
        method = new HeadMethod(uri.toString());
        break;
    case "PUT":
        method = new PutMethod(uri.toString());
        break;
    case "DELETE":
        method = new DeleteMethod(uri.toString());
        break;
    case "TRACE":
        method = new TraceMethod(uri.toString());
        break;
    default:
        throw new IllegalArgumentException("Method not supported: " + req.getMethod());
    }

    setHeaders(method, req.getHeaders());

    for (Cookie cookie : req.getCookies()) {
        // Replace any Zest variables in the value
        cookie.setValue(this.replaceVariablesInString(cookie.getValue(), false));
        httpclient.getState().addCookie(cookie);
    }

    if (req.getMethod().equals("POST")) {
        // The setRequestEntity call trashes any Content-Type specified, so record it and reapply it after
        Header contentType = method.getRequestHeader("Content-Type");
        RequestEntity requestEntity = new StringRequestEntity(req.getData(), null, null);

        ((PostMethod) method).setRequestEntity(requestEntity);

        if (contentType != null) {
            method.setRequestHeader(contentType);
        }
    }

    int code = 0;
    String responseHeader = null;
    String responseBody = null;
    Date start = new Date();
    try {
        this.debug(req.getMethod() + " : " + req.getUrl());
        code = httpclient.executeMethod(method);

        responseHeader = method.getStatusLine().toString() + "\r\n" + arrayToStr(method.getResponseHeaders());
        responseBody = method.getResponseBodyAsString();

    } finally {
        method.releaseConnection();
    }
    // Update the headers with the ones actually sent
    req.setHeaders(arrayToStr(method.getRequestHeaders()));

    if (method.getStatusCode() == 302 && req.isFollowRedirects() && !req.getMethod().equals("GET")) {
        // Follow the redirect 'manually' as the httpclient lib only supports them for GET requests
        method = new GetMethod(method.getResponseHeader("Location").getValue());
        // Just in case there are multiple redirects
        method.setFollowRedirects(req.isFollowRedirects());

        try {
            this.debug(req.getMethod() + " : " + req.getUrl());
            code = httpclient.executeMethod(method);

            responseHeader = method.getStatusLine().toString() + "\r\n"
                    + arrayToStr(method.getResponseHeaders());
            responseBody = method.getResponseBodyAsString();

        } finally {
            method.releaseConnection();
        }
    }

    return new ZestResponse(req.getUrl(), responseHeader, responseBody, code,
            new Date().getTime() - start.getTime());
}

From source file:org.mule.transport.as2.As2MessageDispatcher.java

private void processMuleSession(MuleEvent event, HttpMethod httpMethod) {
    httpMethod.setRequestHeader(new Header(HttpConstants.HEADER_MULE_SESSION,
            event.getMessage().<String>getOutboundProperty(MuleProperties.MULE_SESSION_PROPERTY)));
}

From source file:org.mule.transport.as2.As2MessageDispatcher.java

/**
 * Set AS2 Specific Headers/*w  w w  . j  a v  a 2  s .  com*/
 * */
private void setAS2Headers(MuleEvent event, HttpMethod httpMethod) {
    logger.debug("DBG: inside " + getClass() + ".setAS2Headers()");
    String asTo = as2Connector.getPartnerId();
    logger.debug(AS2Constants.HEADER_TO + ": " + asTo);
    String asFrom = as2Connector.getSenderId();
    logger.debug(AS2Constants.HEADER_FROM + ": " + asFrom);
    String subject = (String) endpoint.getProperty("subject");

    /* N.B. Content-Type is already set in the AS2ObjectToHttpMethodRequest */
    httpMethod.setRequestHeader(
            new Header(AS2Constants.HEADER_CONTENT_DISPOSITION, AS2Constants.HEADER_ATTACHMENT_VALUE));
    httpMethod.setRequestHeader(new Header(AS2Constants.HEADER_FROM, asFrom));
    httpMethod.setRequestHeader(
            new Header(AS2Constants.HEADER_EDIINT_FEATURES, AS2Constants.HEADER_EDIINT_FEATURES_VALUE));
    httpMethod.setRequestHeader(new Header(AS2Constants.HEADER_DATE, new Date().toString()));
    httpMethod.setRequestHeader(new Header(AS2Constants.HEADER_TO, asTo));
    httpMethod.setRequestHeader(new Header(AS2Constants.HEADER_DISPOSITION_NOTIFICATION_TO, asFrom));
    //       httpMethod.setRequestHeader(new Header(AS2Constants.HEADER_SIMPLE_FROM, "qvc@qvc.com"));
    httpMethod.setRequestHeader(new Header(AS2Constants.HEADER_VERSION, AS2Constants.HEADER_AS2_VERSION_VALUE));
    httpMethod.setRequestHeader(
            new Header(AS2Constants.HEADER_MIME_VERSION, AS2Constants.HEADER_MIME_VERSION_VALUE));
    httpMethod.setRequestHeader(new Header(AS2Constants.HEADER_RECIPIENT_ADDRESS,
            endpoint.getEndpointURI().getAddress().replaceFirst("as2", "http")));
    httpMethod.setRequestHeader(new Header(AS2Constants.HEADER_MESSAGE_ID,
            "<AS2_" + RandomStringUtils.randomAlphanumeric(4) + "@" + asFrom + "_" + asTo + ">"));

    if (subject != null) {
        httpMethod.setRequestHeader(new Header(AS2Constants.HEADER_SUBJECT,
                as2Connector.getFilenameParser().getFilename(event.getMessage(), subject)));
    }
    /* Remove MULE Message Headers */
    httpMethod.removeRequestHeader("X-MULE_ENDPOINT");
    httpMethod.removeRequestHeader("X-MULE_ENCODING");
    httpMethod.removeRequestHeader("X-MULE_ROOT_MESSAGE_ID");
    httpMethod.removeRequestHeader("X-MULE_CORRELATION_ID");
    httpMethod.removeRequestHeader("X-MULE_SESSION");
}