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:lucee.commons.net.http.httpclient3.HttpMethodCloner.java

/**
* Clones a HttpMethod. &ltbr>/*ww w . j  ava 2 s.  c  o  m*/
* &ltb&gtAttention:</b> You have to clone a method before it has
* been executed, because the URI can change if followRedirects
* is set to true.
*
* @param m the HttpMethod to clone
*
* @return the cloned HttpMethod, null if the HttpMethod could
* not be instantiated
*
* @throws java.io.IOException if the request body couldn't be read
*/
public static HttpMethod clone(HttpMethod m) {
    HttpMethod copy = null;
    try {
        copy = m.getClass().newInstance();
    } catch (InstantiationException iEx) {
    } catch (IllegalAccessException iaEx) {
    }
    if (copy == null) {
        return null;
    }
    copy.setDoAuthentication(m.getDoAuthentication());
    copy.setFollowRedirects(m.getFollowRedirects());
    copy.setPath(m.getPath());
    copy.setQueryString(m.getQueryString());

    Header[] h = m.getRequestHeaders();
    int size = (h == null) ? 0 : h.length;

    for (int i = 0; i < size; i++) {
        copy.setRequestHeader(new Header(h[i].getName(), h[i].getValue()));
    }
    copy.setStrictMode(m.isStrictMode());
    if (m instanceof HttpMethodBase) {
        copyHttpMethodBase((HttpMethodBase) m, (HttpMethodBase) copy);
    }
    if (m instanceof EntityEnclosingMethod) {
        copyEntityEnclosingMethod((EntityEnclosingMethod) m, (EntityEnclosingMethod) copy);
    }
    return copy;
}

From source file:com.discursive.jccook.httpclient.ConditionalGetExample.java

private void setHeaders(HttpMethod method) {
    method.setRequestHeader(new Header("If-None-Match", entityTag));
    method.setRequestHeader(new Header("If-Modified-Since", lastModified));
}

From source file:net.sf.ehcache.constructs.web.filter.PageFragmentCachingFilterTest.java

/**
 * Tests that a page which is not storeGzipped is not gzipped when the user agent does not accept gzip encoding
 *//*from  ww  w  .j  a v a 2  s.  co  m*/
public void testNotGzippedWhenNotAcceptEncodingPageFragment() throws Exception {
    HttpClient httpClient = new HttpClient();
    HttpMethod httpMethod = new GetMethod(buildUrl("/include/Footer.jsp"));
    httpMethod.setRequestHeader(new Header("Accept-encoding", "gzip"));
    httpClient.executeMethod(httpMethod);
    byte[] responseBody = httpMethod.getResponseBody();
    assertFalse(PageInfo.isGzipped(responseBody));
    assertNotSame("gzip", httpMethod.getResponseHeader("Accept-encoding"));
}

From source file:com.cyberway.issue.httpclient.HttpRecorderMethod.java

/**
 * If a 'Proxy-Connection' header has been added to the request,
 * it'll be of a 'keep-alive' type.  Until we support 'keep-alives',
 * override the Proxy-Connection setting and instead pass a 'close'
 * (Otherwise every request has to timeout before we notice
 * end-of-document).//from w  w w  . j  ava 2  s. com
 * @param method Method to find proxy-connection header in.
 */
public void handleAddProxyConnectionHeader(HttpMethod method) {
    Header h = method.getRequestHeader("Proxy-Connection");
    if (h != null) {
        h.setValue("close");
        method.setRequestHeader(h);
    }
}

From source file:ch.ksfx.web.services.spidering.http.HttpClientHelper.java

private HttpMethod executeMethod(HttpMethod httpMethod) {
    for (Header header : this.headers.getHeaders()) {
        httpMethod.setRequestHeader(header);
    }// www.  j  ava 2 s.co  m

    httpMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new KsfxHttpRetryHandler(retryCount, retryDelay));

    try {
        int tryCount = 0;
        int statusCode;
        do {
            if (tryCount > 1) {
                httpMethod = createNewHttpMethod(httpMethod);
                try {
                    if (retryDelay == 0) {
                        retryDelay = DEFAULT_RETRY_DELAY;
                    }
                    Thread.sleep(retryDelay);
                } catch (InterruptedException e) {
                    logger.severe("InterruptedException");
                }
            }

            //PROXY Configuration
            /*
            if (torify) {
                    
            String proxyHost = "";
            Integer proxyPort = 0;
                    
            try {
                    proxyHost = SpiderConfiguration.getConfiguration().getString("torifyHost");
                    proxyPort = SpiderConfiguration.getConfiguration().getInt("torifyPort");
            } catch (Exception e) {
                logger.severe("Cannot get Proxy information");
            }
                    
            this.httpClient.getHostConfiguration().setProxy(proxyHost, proxyPort);
            }
            */

            statusCode = this.httpClient.executeMethod(httpMethod);
            tryCount++;
        } while (!(statusCode == HttpStatus.SC_OK || statusCode == HttpStatus.SC_FORBIDDEN
                || statusCode == HttpStatus.SC_NOT_FOUND) && tryCount < retryCount);
        if (statusCode != HttpStatus.SC_OK) {
            System.out.println("HTTP method failed: " + httpMethod.getStatusLine() + " - "
                    + httpMethod.getURI().toString());
        }
    } catch (HttpException e) {
        e.printStackTrace();
        httpMethod.abort();
        try {
            logger.log(Level.SEVERE, "Redirrex " + e.getClass(), e);
            if (e.getClass().equals(RedirectException.class)) {
                logger.log(Level.SEVERE, "Is real redirect exception", e);
                throw new RuntimeException("HttpRedirectException");
            }
            logger.log(Level.SEVERE, "HTTP protocol error for URL: " + httpMethod.getURI().toString(), e);
        } catch (URIException e1) {
            e.printStackTrace();
            logger.log(Level.SEVERE, "URI exception", e);
        }
        throw new RuntimeException("HttpException");
    } catch (IOException e) {
        try {
            e.printStackTrace();
            logger.log(Level.SEVERE, "HTTP transport error for URL: " + httpMethod.getURI().toString(), e);

        } catch (URIException e1) {
            e.printStackTrace();
            logger.log(Level.SEVERE, "URI exception", e);

        }
        throw new RuntimeException("IOException");
    }
    return httpMethod;
}

From source file:net.sf.ehcache.constructs.web.filter.CachingFilterTest.java

/**
 * Tests whether the page is gzipped using the rawer HttpClient library.
 * Lets us check that the responseBody is really gzipped.
 *///from  w ww.  j  a va 2s .c o  m
public void testCachedPageIsGzippedWhenEncodingHeaderSet() throws IOException {
    HttpClient httpClient = new HttpClient();
    HttpMethod httpMethod = new GetMethod(buildUrl(cachedPageUrl));
    httpMethod.setRequestHeader(new Header("Accept-encoding", "gzip"));
    httpClient.executeMethod(httpMethod);
    byte[] responseBody = httpMethod.getResponseBody();
    assertTrue(PageInfo.isGzipped(responseBody));
}

From source file:net.sf.ehcache.constructs.web.filter.SimpleCachingHeadersPageCachingFilterTest.java

/**
 * Tests whether the page is gzipped using the rawer HttpClient library.
 * Lets us check that the responseBody is really gzipped.
 *///  ww  w .  j  a  v  a  2s .c o  m
@Test
public void testCachedPageIsGzippedWhenEncodingHeaderSet() throws IOException {
    HttpClient httpClient = new HttpClient();
    HttpMethod httpMethod = new GetMethod(buildUrl(cachedPageUrl));
    httpMethod.setRequestHeader(new Header("Accept-encoding", "gzip"));
    httpClient.executeMethod(httpMethod);
    byte[] responseBody = httpMethod.getResponseBody();
    assertTrue(PageInfo.isGzipped(responseBody));
}

From source file:com.zimbra.cs.dav.service.DavServlet.java

private boolean isProxyRequest(DavContext ctxt, DavMethod m)
        throws IOException, DavException, ServiceException {
    Provisioning prov = Provisioning.getInstance();
    ItemId target = null;/*  w ww.j  av  a  2  s . c o m*/
    String extraPath = null;
    String requestPath = ctxt.getPath();
    try {
        if (ctxt.getUser() == null) {
            return false;
        }
        if (requestPath == null || requestPath.length() < 2) {
            return false;
        }
        Account account = prov.getAccountByName(ctxt.getUser());
        if (account == null) {
            return false;
        }
        Mailbox mbox = MailboxManager.getInstance().getMailboxByAccount(account);
        Pair<Folder, String> match = mbox.getFolderByPathLongestMatch(ctxt.getOperationContext(),
                Mailbox.ID_FOLDER_USER_ROOT, requestPath);
        Folder targetFolder = match.getFirst();
        if (!(targetFolder instanceof Mountpoint)) {
            return false;
        }
        Mountpoint mp = (Mountpoint) targetFolder;
        target = new ItemId(mp.getOwnerId(), mp.getRemoteId());
        extraPath = match.getSecond();
    } catch (ServiceException e) {
        ZimbraLog.dav.debug("can't get path", e);
        return false;
    }

    // we don't proxy zero depth PROPFIND, and all PROPPATCH on mountpoints,
    // because the mountpoint object contains WebDAV properties that are
    // private to the user.
    // we also don't proxy DELETE on a mountpoint.
    if (extraPath == null && (m.getName().equals(PropFind.PROPFIND) && ctxt.getDepth() == DavContext.Depth.zero
            || m.getName().equals(PropPatch.PROPPATCH) || m.getName().equals(Delete.DELETE))) {
        return false;
    }

    String prefix = ctxt.getPath();
    if (extraPath != null) {
        prefix = prefix.substring(0, prefix.indexOf(extraPath));
    }
    prefix = HttpUtil.urlEscape(DAV_PATH + "/" + ctxt.getUser() + prefix);

    if (!prefix.endsWith("/")) {
        prefix += "/";
    }

    // make sure the target account exists.
    Account acct = prov.getAccountById(target.getAccountId());
    if (acct == null) {
        return false;
    }
    Server server = prov.getServer(acct);
    if (server == null) {
        return false;
    }

    // get the path to the target mail item
    AuthToken authToken = AuthProvider.getAuthToken(ctxt.getAuthAccount());
    ZMailbox.Options zoptions = new ZMailbox.Options(authToken.toZAuthToken(), AccountUtil.getSoapUri(acct));
    zoptions.setNoSession(true);
    zoptions.setTargetAccount(target.getAccountId());
    zoptions.setTargetAccountBy(Key.AccountBy.id);
    ZMailbox zmbx = ZMailbox.getMailbox(zoptions);
    ZFolder f = zmbx.getFolderById("" + target.toString());
    if (f == null) {
        return false;
    }
    String path = f.getPath();
    String newPrefix = HttpUtil.urlEscape(DAV_PATH + "/" + acct.getName() + f.getPath());

    if (ctxt.hasRequestMessage()) {
        // replace the path in <href> of the request with the path to the target mail item.
        Document req = ctxt.getRequestMessage();
        for (Object hrefObj : req.getRootElement().elements(DavElements.E_HREF)) {
            if (!(hrefObj instanceof Element)) {
                continue;
            }
            Element href = (Element) hrefObj;
            String v = href.getText();
            // prefix matching is not as straightforward as we have jetty redirect from /dav to /home/dav.
            href.setText(newPrefix + "/" + v.substring(v.lastIndexOf('/') + 1));
        }
    }

    // build proxy request
    String url = getProxyUrl(ctxt.getRequest(), server, DAV_PATH)
            + HttpUtil.urlEscape("/" + acct.getName() + path + "/" + (extraPath == null ? "" : extraPath));
    HttpState state = new HttpState();
    authToken.encode(state, false, server.getAttr(Provisioning.A_zimbraServiceHostname));
    HttpClient client = ZimbraHttpConnectionManager.getInternalHttpConnMgr().newHttpClient();
    client.setState(state);
    HttpMethod method = m.toHttpMethod(ctxt, url);
    method.setRequestHeader(new Header(DavProtocol.HEADER_USER_AGENT, "Zimbra-DAV/" + BuildInfo.VERSION));
    if (ZimbraLog.dav.isDebugEnabled()) {
        Enumeration<String> headers = ctxt.getRequest().getHeaderNames();
        while (headers.hasMoreElements()) {
            String hdr = headers.nextElement();
            if (!PROXY_REQUEST_HEADERS.contains(hdr) && !IGNORABLE_PROXY_REQUEST_HEADERS.contains(hdr)) {
                ZimbraLog.dav.debug(
                        "Dropping header(s) with name [%s] from proxy request (not in PROXY_REQUEST_HEADERS)",
                        hdr);
            }
        }
    }

    for (String h : PROXY_REQUEST_HEADERS) {
        String hval = ctxt.getRequest().getHeader(h);
        if (hval != null) {
            method.addRequestHeader(h, hval);
        }
    }
    int statusCode = HttpClientUtil.executeMethod(client, method);
    if (ZimbraLog.dav.isDebugEnabled()) {
        for (Header hval : method.getResponseHeaders()) {
            String hdrName = hval.getName();
            if (!PROXY_RESPONSE_HEADERS.contains(hdrName)
                    && !IGNORABLE_PROXY_RESPONSE_HEADERS.contains(hdrName)) {
                ZimbraLog.dav.debug("Dropping header [%s] from proxy response (not in PROXY_RESPONSE_HEADERS)",
                        hval);
            }
        }
    }

    for (String h : PROXY_RESPONSE_HEADERS) {
        for (Header hval : method.getResponseHeaders(h)) {
            String hdrValue = hval.getValue();
            if (DavProtocol.HEADER_LOCATION.equals(h)) {
                int pfxLastSlashPos = prefix.lastIndexOf('/');
                int lastSlashPos = hdrValue.lastIndexOf('/');
                if ((lastSlashPos > 0) && (pfxLastSlashPos > 0)) {
                    hdrValue = prefix.substring(0, pfxLastSlashPos) + hdrValue.substring(lastSlashPos);
                    ZimbraLog.dav.debug("Original [%s] from proxy response new value '%s'", hval, hdrValue);
                }
            }
            ctxt.getResponse().addHeader(h, hdrValue);
        }
    }

    ctxt.getResponse().setStatus(statusCode);
    ctxt.setStatus(statusCode);
    try (InputStream in = method.getResponseBodyAsStream()) {
        switch (statusCode) {
        case DavProtocol.STATUS_MULTI_STATUS:
            // rewrite the <href> element in the response to point to local mountpoint.
            try {
                Document response = W3cDomUtil.parseXMLToDom4jDocUsingSecureProcessing(in);
                Element top = response.getRootElement();
                for (Object responseObj : top.elements(DavElements.E_RESPONSE)) {
                    if (!(responseObj instanceof Element)) {
                        continue;
                    }
                    Element href = ((Element) responseObj).element(DavElements.E_HREF);
                    String v = href.getText();
                    v = URLDecoder.decode(v);
                    // Bug:106438, because v contains URL encoded value(%40) for '@' the comparison fails
                    if (v.startsWith(newPrefix)) {
                        href.setText(prefix + v.substring(newPrefix.length() + 1));
                    }
                }
                if (ZimbraLog.dav.isDebugEnabled()) {
                    ZimbraLog.dav.debug("PROXY RESPONSE:\n%s", new String(DomUtil.getBytes(response), "UTF-8"));
                }
                DomUtil.writeDocumentToStream(response, ctxt.getResponse().getOutputStream());
                ctxt.responseSent();
            } catch (XmlParseException e) {
                ZimbraLog.dav.warn("proxy request failed", e);
                return false;
            }
            break;
        default:
            if (in != null) {
                ByteUtil.copy(in, true, ctxt.getResponse().getOutputStream(), false);
            }
            ctxt.responseSent();
            break;
        }
        return true;
    }
}

From source file:freeciv.servlet.ProxyServlet.java

/**
 * Retreives all of the headers from the servlet request and sets them on
 * the proxy request/* w  ww. 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:io.fabric8.gateway.servlet.ProxyServlet.java

/**
 * Retrieves all of the headers from the servlet request and sets them on
 * the proxy request/*from w  w w  . j av a 2 s .co  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);
        }
    }
}