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:com.sourcesense.confluence.servlets.CMISProxyServlet.java

/**
 * Retrieves all of the headers from the servlet request and sets them on
 * the proxy request//w ww.  j  a  va  2  s  .co m
 *
 * @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
 */
@SuppressWarnings("unchecked")
private void setProxyRequestHeaders(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)) {
            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 = getProxyHostAndPort(httpServletRequest);
            }
            Header header = new Header(stringHeaderName, stringHeaderValue);
            // Set the same header on the proxy request
            httpMethodProxyRequest.setRequestHeader(header);
        }
    }
}

From source file:com.qlkh.client.server.proxy.ProxyServlet.java

/**
 * Retrieves all of the headers from the servlet request and sets them on
 * the proxy request/*from   www. j  a  va2 s .c  o m*/
 *
 * @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
 */
@SuppressWarnings("unchecked")
private void setProxyRequestHeaders(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)) {
            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 = getProxyHostAndPort();
            }
            Header header = new Header(stringHeaderName, stringHeaderValue);
            // Set the same header on the proxy request
            httpMethodProxyRequest.setRequestHeader(header);
        }
    }
}

From source file:ir.keloud.android.lib.common.KeloudClient.java

private int patchRedirection(int status, HttpMethod method) throws HttpException, IOException {
    int redirectionsCount = 0;
    while (redirectionsCount < MAX_REDIRECTIONS_COUNT && (status == HttpStatus.SC_MOVED_PERMANENTLY
            || status == HttpStatus.SC_MOVED_TEMPORARILY || status == HttpStatus.SC_TEMPORARY_REDIRECT)) {

        Header location = method.getResponseHeader("Location");
        if (location == null) {
            location = method.getResponseHeader("location");
        }/*from ww w. jav a2 s  .co m*/
        if (location != null) {
            Log_OC.d(TAG + " #" + mInstanceNumber, "Location to redirect: " + location.getValue());

            // Release the connection to avoid reach the max number of connections per host
            // due to it will be set a different url
            exhaustResponse(method.getResponseBodyAsStream());
            method.releaseConnection();

            method.setURI(new URI(location.getValue(), true));
            Header destination = method.getRequestHeader("Destination");
            if (destination == null) {
                destination = method.getRequestHeader("destination");
            }
            if (destination != null) {
                String locationStr = location.getValue();
                int suffixIndex = locationStr
                        .lastIndexOf((mCredentials instanceof KeloudBearerCredentials) ? AccountUtils.ODAV_PATH
                                : AccountUtils.WEBDAV_PATH_4_0);
                String redirectionBase = locationStr.substring(0, suffixIndex);

                String destinationStr = destination.getValue();
                String destinationPath = destinationStr.substring(mBaseUri.toString().length());
                String redirectedDestination = redirectionBase + destinationPath;

                destination.setValue(redirectedDestination);
                method.setRequestHeader(destination);
            }
            status = super.executeMethod(method);
            redirectionsCount++;

        } else {
            Log_OC.d(TAG + " #" + mInstanceNumber, "No location to redirect!");
            status = HttpStatus.SC_NOT_FOUND;
        }
    }
    return status;
}

From source file:com.owncloud.android.lib.common.OwnCloudClient.java

private int patchRedirection(int status, HttpMethod method) throws HttpException, IOException {
    int redirectionsCount = 0;
    while (redirectionsCount < MAX_REDIRECTIONS_COUNT && (status == HttpStatus.SC_MOVED_PERMANENTLY
            || status == HttpStatus.SC_MOVED_TEMPORARILY || status == HttpStatus.SC_TEMPORARY_REDIRECT)) {

        Header location = method.getResponseHeader("Location");
        if (location == null) {
            location = method.getResponseHeader("location");
        }// w  ww.  ja  v a2 s .co m
        if (location != null) {
            Log_OC.d(TAG + " #" + mInstanceNumber, "Location to redirect: " + location.getValue());

            // Release the connection to avoid reach the max number of connections per host
            // due to it will be set a different url
            exhaustResponse(method.getResponseBodyAsStream());
            method.releaseConnection();

            method.setURI(new URI(location.getValue(), true));
            Header destination = method.getRequestHeader("Destination");
            if (destination == null) {
                destination = method.getRequestHeader("destination");
            }
            if (destination != null) {
                String locationStr = location.getValue();
                int suffixIndex = locationStr.lastIndexOf(
                        (mCredentials instanceof OwnCloudBearerCredentials) ? AccountUtils.ODAV_PATH
                                : AccountUtils.WEBDAV_PATH_4_0);
                String redirectionBase = locationStr.substring(0, suffixIndex);

                String destinationStr = destination.getValue();
                String destinationPath = destinationStr.substring(mBaseUri.toString().length());
                String redirectedDestination = redirectionBase + destinationPath;

                destination.setValue(redirectedDestination);
                method.setRequestHeader(destination);
            }
            status = super.executeMethod(method);
            redirectionsCount++;

        } else {
            Log_OC.d(TAG + " #" + mInstanceNumber, "No location to redirect!");
            status = HttpStatus.SC_NOT_FOUND;
        }
    }
    return status;
}

From source file:com.cerema.cloud2.lib.common.OwnCloudClient.java

public RedirectionPath followRedirection(HttpMethod method) throws IOException {
    int redirectionsCount = 0;
    int status = method.getStatusCode();
    RedirectionPath result = new RedirectionPath(status, MAX_REDIRECTIONS_COUNT);
    while (redirectionsCount < MAX_REDIRECTIONS_COUNT && (status == HttpStatus.SC_MOVED_PERMANENTLY
            || status == HttpStatus.SC_MOVED_TEMPORARILY || status == HttpStatus.SC_TEMPORARY_REDIRECT)) {

        Header location = method.getResponseHeader("Location");
        if (location == null) {
            location = method.getResponseHeader("location");
        }//from  w w  w.java 2 s . co  m
        if (location != null) {
            Log_OC.d(TAG + " #" + mInstanceNumber, "Location to redirect: " + location.getValue());

            String locationStr = location.getValue();
            result.addLocation(locationStr);

            // Release the connection to avoid reach the max number of connections per host
            // due to it will be set a different url
            exhaustResponse(method.getResponseBodyAsStream());
            method.releaseConnection();

            method.setURI(new URI(locationStr, true));
            Header destination = method.getRequestHeader("Destination");
            if (destination == null) {
                destination = method.getRequestHeader("destination");
            }
            if (destination != null) {
                int suffixIndex = locationStr.lastIndexOf(
                        (mCredentials instanceof OwnCloudBearerCredentials) ? AccountUtils.ODAV_PATH
                                : AccountUtils.WEBDAV_PATH_4_0);
                String redirectionBase = locationStr.substring(0, suffixIndex);

                String destinationStr = destination.getValue();
                String destinationPath = destinationStr.substring(mBaseUri.toString().length());
                String redirectedDestination = redirectionBase + destinationPath;

                destination.setValue(redirectedDestination);
                method.setRequestHeader(destination);
            }
            status = super.executeMethod(method);
            result.addStatus(status);
            redirectionsCount++;

        } else {
            Log_OC.d(TAG + " #" + mInstanceNumber, "No location to redirect!");
            status = HttpStatus.SC_NOT_FOUND;
        }
    }
    return result;
}

From source file:com.mirth.connect.connectors.http.HttpMessageDispatcher.java

private HttpMethod buildHttpRequest(String address, MessageObject mo) throws Exception {
    String method = connector.getDispatcherMethod();
    String content = replacer.replaceValues(connector.getDispatcherContent(), mo);
    String contentType = connector.getDispatcherContentType();
    String charset = connector.getDispatcherCharset();
    boolean isMultipart = connector.isDispatcherMultipart();
    Map<String, String> headers = replacer.replaceValuesInMap(connector.getDispatcherHeaders(), mo);
    Map<String, String> parameters = replacer.replaceValuesInMap(connector.getDispatcherParameters(), mo);

    HttpMethod httpMethod = null;

    // populate the query parameters
    NameValuePair[] queryParameters = new NameValuePair[parameters.size()];
    int index = 0;

    for (Entry<String, String> parameterEntry : parameters.entrySet()) {
        queryParameters[index] = new NameValuePair(parameterEntry.getKey(), parameterEntry.getValue());
        index++;/*from   www  .  j a  v a 2s  .c o m*/
        logger.debug("setting query parameter: [" + parameterEntry.getKey() + ", " + parameterEntry.getValue()
                + "]");
    }

    // create the method
    if ("GET".equalsIgnoreCase(method)) {
        httpMethod = new GetMethod(address);
        httpMethod.setQueryString(queryParameters);
    } else if ("POST".equalsIgnoreCase(method)) {
        PostMethod postMethod = new PostMethod(address);

        if (isMultipart) {
            logger.debug("setting multipart file content");
            File tempFile = File.createTempFile(UUID.randomUUID().toString(), ".tmp");
            FileUtils.writeStringToFile(tempFile, content, charset);
            Part[] parts = new Part[] { new FilePart(tempFile.getName(), tempFile, contentType, charset) };
            postMethod.setQueryString(queryParameters);
            postMethod.setRequestEntity(new MultipartRequestEntity(parts, postMethod.getParams()));
        } else if (StringUtils.equals(contentType, "application/x-www-form-urlencoded")) {
            postMethod.setRequestBody(queryParameters);
        } else {
            postMethod.setQueryString(queryParameters);
            postMethod.setRequestEntity(new StringRequestEntity(content, contentType, charset));
        }

        httpMethod = postMethod;
    } else if ("PUT".equalsIgnoreCase(method)) {
        PutMethod putMethod = new PutMethod(address);
        putMethod.setRequestEntity(new StringRequestEntity(content, contentType, charset));
        putMethod.setQueryString(queryParameters);
        httpMethod = putMethod;
    } else if ("DELETE".equalsIgnoreCase(method)) {
        httpMethod = new DeleteMethod(address);
        httpMethod.setQueryString(queryParameters);
    }

    // set the headers
    for (Entry<String, String> headerEntry : headers.entrySet()) {
        httpMethod.setRequestHeader(new Header(headerEntry.getKey(), headerEntry.getValue()));
        logger.debug("setting method header: [" + headerEntry.getKey() + ", " + headerEntry.getValue() + "]");
    }

    return httpMethod;
}

From source file:it.geosdi.era.server.servlet.HTTPProxy.java

/**
 * Retreives all of the headers from the servlet request and sets them on
 * the proxy request/* ww w  . java 2  s  .  c  o m*/
 * 
 * @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
 */
@SuppressWarnings("unchecked")
private void setProxyRequestHeaders(URL url, HttpServletRequest httpServletRequest,
        HttpMethod httpMethodProxyRequest) {
    this.stringProxyHost = url.getHost();
    this.intProxyPort = url.getPort();
    this.stringProxyPath = url.getPath();

    // 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))
            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 = getProxyHostAndPort();
            }
            // Skip GZIP Responses
            if (stringHeaderName.equalsIgnoreCase(HTTP_HEADER_ACCEPT_ENCODING)
                    && stringHeaderValue.toLowerCase().contains("gzip"))
                continue;
            if (stringHeaderName.equalsIgnoreCase(HTTP_HEADER_CONTENT_ENCODING)
                    && stringHeaderValue.toLowerCase().contains("gzip"))
                continue;
            if (stringHeaderName.equalsIgnoreCase(HTTP_HEADER_TRANSFER_ENCODING))
                continue;
            Header header = new Header(stringHeaderName, stringHeaderValue);
            // Set the same header on the proxy request
            httpMethodProxyRequest.setRequestHeader(header);
        }
    }
}

From source file:com.twinsoft.convertigo.engine.servlets.ReverseProxyServlet.java

/**
 * Retrieves all of the headers from the servlet request and sets them on
 * the proxy request/*www  . j a  v  a2 s .  co m*/
 * 
 * @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
 */
private void setProxyRequestHeaders(HttpServletRequest httpServletRequest, HttpMethod httpMethodProxyRequest,
        ProxyHttpConnector proxyHttpConnector) {
    Collection<String> removableHeaders = proxyHttpConnector.getRemovableHeadersSet();
    // Get an Enumeration of all of the header names sent by the client
    Enumeration<String> enumerationOfHeaderNames = GenericUtils.cast(httpServletRequest.getHeaderNames());
    while (enumerationOfHeaderNames.hasMoreElements()) {
        String stringHeaderName = (String) enumerationOfHeaderNames.nextElement();
        if (stringHeaderName.equalsIgnoreCase(STRING_CONTENT_LENGTH_HEADER_NAME)
                || stringHeaderName.equalsIgnoreCase("Cookie")
                || removableHeaders.contains(stringHeaderName.toLowerCase())) {
            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 = GenericUtils
                .cast(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 = getProxyHostAndPort(proxyHttpConnector);
            } else if (stringHeaderName.equalsIgnoreCase("Referer")) {
                stringHeaderValue = stringHeaderValue.replaceFirst("://[^/]*/[^/]*/",
                        "://" + getProxyHostAndPort(proxyHttpConnector) + proxyHttpConnector.getBaseDir()
                                + (proxyHttpConnector.getBaseDir().endsWith("/") ? "" : "/"));
            }
            Engine.logEngine.debug(
                    "(ReverseProxyServlet) Forwarding header: " + stringHeaderName + "=" + stringHeaderValue);
            Header header = new Header(stringHeaderName, stringHeaderValue);
            // Set the same header on the proxy request
            httpMethodProxyRequest.setRequestHeader(header);
        }
    }
}

From source file:it.geosolutions.httpproxy.HTTPProxy.java

/**
 * Retrieves all of the headers from the servlet request and sets them on the proxy request
 * /*  ww w  .j av  a2  s .  c om*/
 * @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
 * @return ProxyInfo
 */
@SuppressWarnings("rawtypes")
private ProxyInfo setProxyRequestHeaders(URL url, HttpServletRequest httpServletRequest,
        HttpMethod httpMethodProxyRequest) {

    final String proxyHost = url.getHost();
    final int proxyPort = url.getPort();
    final String proxyPath = url.getPath();
    final ProxyInfo proxyInfo = new ProxyInfo(proxyHost, proxyPath, proxyPort);

    // ////////////////////////////////////////
    // 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(Utils.CONTENT_LENGTH_HEADER_NAME))
            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(Utils.HOST_HEADER_NAME)) {
                stringHeaderValue = Utils.getProxyHostAndPort(proxyInfo);
            }

            // ////////////////////////
            // Skip GZIP Responses
            // ////////////////////////

            if (stringHeaderName.equalsIgnoreCase(Utils.HTTP_HEADER_ACCEPT_ENCODING)
                    && stringHeaderValue.toLowerCase().contains("gzip"))
                continue;
            if (stringHeaderName.equalsIgnoreCase(Utils.HTTP_HEADER_CONTENT_ENCODING)
                    && stringHeaderValue.toLowerCase().contains("gzip"))
                continue;
            if (stringHeaderName.equalsIgnoreCase(Utils.HTTP_HEADER_TRANSFER_ENCODING))
                continue;

            Header header = new Header(stringHeaderName, stringHeaderValue);

            // /////////////////////////////////////////////
            // Set the same header on the proxy request
            // /////////////////////////////////////////////

            httpMethodProxyRequest.setRequestHeader(header);
        }
    }

    return proxyInfo;
}

From source file:org.abstracthorizon.proximity.storage.remote.CommonsHttpClientRemotePeer.java

/**
 * Execute method./*from  ww w .  j a va2  s.c o  m*/
 * 
 * @param method the method
 * 
 * @return the int
 */
protected int executeMethod(HttpMethod method) {
    if (getUserAgentString() != null) {
        method.setRequestHeader(new Header("user-agent", getUserAgentString()));
    }
    method.setRequestHeader(new Header("accept", "*/*"));
    method.setRequestHeader(new Header("accept-language", "en-us"));
    method.setRequestHeader(new Header("accept-encoding", "gzip, identity"));
    method.setRequestHeader(new Header("connection", "Keep-Alive"));
    method.setRequestHeader(new Header("cache-control", "no-cache"));
    // TODO: fix for #93
    // method.setFollowRedirects(isFollowRedirection());
    method.setFollowRedirects(true);
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, httpRetryHandler);
    method.setQueryString(getQueryString());
    int resultCode = 0;
    try {
        resultCode = getHttpClient().executeMethod(httpConfiguration, method);
    } catch (HttpException ex) {
        logger.error("Protocol error while executing " + method.getName() + " method", ex);
    } catch (IOException ex) {
        logger.error("Tranport error while executing " + method.getName() + " method", ex);
    }
    return resultCode;
}