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(String paramString1, String paramString2);

Source Link

Usage

From source file:org.apache.hadoop.yarn.server.webproxy.WebAppProxyServlet.java

/**
 * Download link and have it be the response.
 * @param req the http request/* www .ja v a  2 s  . c o m*/
 * @param resp the http response
 * @param link the link to download
 * @param c the cookie to set if any
 * @throws IOException on any error.
 */
private static void proxyLink(HttpServletRequest req, HttpServletResponse resp, URI link, Cookie c,
        String proxyHost) throws IOException {
    org.apache.commons.httpclient.URI uri = new org.apache.commons.httpclient.URI(link.toString(), false);
    HttpClientParams params = new HttpClientParams();
    params.setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
    params.setBooleanParameter(HttpClientParams.ALLOW_CIRCULAR_REDIRECTS, true);
    HttpClient client = new HttpClient(params);
    // Make sure we send the request from the proxy address in the config
    // since that is what the AM filter checks against. IP aliasing or
    // similar could cause issues otherwise.
    HostConfiguration config = new HostConfiguration();
    InetAddress localAddress = InetAddress.getByName(proxyHost);
    if (LOG.isDebugEnabled()) {
        LOG.debug("local InetAddress for proxy host: " + localAddress.toString());
    }
    config.setLocalAddress(localAddress);
    HttpMethod method = new GetMethod(uri.getEscapedURI());
    @SuppressWarnings("unchecked")
    Enumeration<String> names = req.getHeaderNames();
    while (names.hasMoreElements()) {
        String name = names.nextElement();
        if (passThroughHeaders.contains(name)) {
            String value = req.getHeader(name);
            LOG.debug("REQ HEADER: " + name + " : " + value);
            method.setRequestHeader(name, value);
        }
    }

    String user = req.getRemoteUser();
    if (user != null && !user.isEmpty()) {
        method.setRequestHeader("Cookie", PROXY_USER_COOKIE_NAME + "=" + URLEncoder.encode(user, "ASCII"));
    }
    OutputStream out = resp.getOutputStream();
    try {
        resp.setStatus(client.executeMethod(config, method));
        for (Header header : method.getResponseHeaders()) {
            resp.setHeader(header.getName(), header.getValue());
        }
        if (c != null) {
            resp.addCookie(c);
        }
        InputStream in = method.getResponseBodyAsStream();
        if (in != null) {
            IOUtils.copyBytes(in, out, 4096, true);
        }
    } finally {
        method.releaseConnection();
    }
}

From source file:org.apache.jackrabbit.spi2dav.RepositoryServiceImpl.java

protected static void initMethod(HttpMethod method, SessionInfo sessionInfo, boolean addIfHeader)
        throws RepositoryException {
    if (addIfHeader) {
        checkSessionInfo(sessionInfo);/*  w  ww  . j  a va 2 s .c  om*/
        Set<String> allLockTokens = ((SessionInfoImpl) sessionInfo).getAllLockTokens();
        // TODO: ev. build tagged if header
        if (!allLockTokens.isEmpty()) {
            String[] locktokens = allLockTokens.toArray(new String[allLockTokens.size()]);
            IfHeader ifH = new IfHeader(locktokens);
            method.setRequestHeader(ifH.getHeaderName(), ifH.getHeaderValue());
        }
    }

    initMethod(method, sessionInfo);
}

From source file:org.apache.jackrabbit.spi2davex.RepositoryServiceImpl.java

private static void addIfHeader(SessionInfo sInfo, HttpMethod method) {
    String[] locktokens = sInfo.getLockTokens();
    if (locktokens != null && locktokens.length > 0) {
        IfHeader ifH = new IfHeader(locktokens);
        method.setRequestHeader(ifH.getHeaderName(), ifH.getHeaderValue());
    }/* w  w  w  . jav  a2s  .com*/
}

From source file:org.apache.jmeter.protocol.amf.sampler.AmfRequest.java

protected void setDefaultRequestHeaders(HttpMethod httpMethod) {
    httpMethod.setRequestHeader("Cache-Control", "no-cache");
    httpMethod.setRequestHeader("Accept", "*/*");
    httpMethod.setRequestHeader("Accept-Encoding", "gzip, deflate");
}

From source file:org.apache.jmeter.protocol.http.control.CacheManager.java

/**
 * Check the cache, and if there is a match, set the headers:
 * <ul>/*from   w  w w. j  av  a 2s .co m*/
 * <li>If-Modified-Since</li>
 * <li>If-None-Match</li>
 * </ul>
 * Commons HttpClient version
 * @param url URL to look up in cache
 * @param method where to set the headers
 * @deprecated HC3.1 will be dropped in upcoming version
 */
@Deprecated
public void setHeaders(URL url, HttpMethod method) {
    CacheEntry entry = getCache().get(url.toString());
    if (log.isDebugEnabled()) {
        log.debug(method.getName() + "(OACH) " + url.toString() + " " + entry);
    }
    if (entry != null) {
        final String lastModified = entry.getLastModified();
        if (lastModified != null) {
            method.setRequestHeader(HTTPConstants.IF_MODIFIED_SINCE, lastModified);
        }
        final String etag = entry.getEtag();
        if (etag != null) {
            method.setRequestHeader(HTTPConstants.IF_NONE_MATCH, etag);
        }
    }
}

From source file:org.apache.jmeter.protocol.http.sampler.HTTPHC3Impl.java

/**
 * Extracts all the required cookies for that particular URL request and
 * sets them in the <code>HttpMethod</code> passed in.
 *
 * @param method <code>HttpMethod</code> for the request
 * @param u <code>URL</code> of the request
 * @param cookieManager the <code>CookieManager</code> containing all the cookies
 * @return a String containing the cookie details (for the response)
 * May be null//from   w  w  w .  j  av a2 s .c o  m
 */
private String setConnectionCookie(HttpMethod method, URL u, CookieManager cookieManager) {
    String cookieHeader = null;
    if (cookieManager != null) {
        cookieHeader = cookieManager.getCookieHeaderForURL(u);
        if (cookieHeader != null) {
            method.setRequestHeader(HTTPConstants.HEADER_COOKIE, cookieHeader);
        }
    }
    return cookieHeader;
}

From source file:org.apache.maven.wagon.providers.webdav.CorrectedWebdavResource.java

/**
 * Add all additionals headers that have been previously registered with addRequestHeader to the method
 *///from w ww .  j a v a  2  s .co  m
protected void generateAdditionalHeaders(HttpMethod method) {
    Iterator iterator = getHeaders().keySet().iterator();
    while (iterator.hasNext()) {
        String header = (String) iterator.next();
        method.setRequestHeader(header, (String) getHeaders().get(header));
    }
}

From source file:org.apache.oodt.cas.filemgr.catalog.solr.SolrClient.java

/**
 * Common functionality for HTTP GET and POST requests.
 * @param method//w w  w.  j  a  va2  s . c  o m
 * @return
 * @throws Exception
 */
private String doHttp(HttpMethod method) throws IOException, CatalogException {

    StringBuilder response = new StringBuilder();
    BufferedReader br = null;
    try {

        // send request
        HttpClient httpClient = new HttpClient();
        // OODT-719 Prevent httpclient from spawning closewait tcp connections
        method.setRequestHeader("Connection", "close");

        int statusCode = httpClient.executeMethod(method);

        // read response
        if (statusCode != HttpStatus.SC_OK) {

            // still consume the response
            method.getResponseBodyAsString();
            throw new CatalogException("HTTP method failed: " + method.getStatusLine());

        } else {

            // read the response body.
            br = new BufferedReader(new InputStreamReader(method.getResponseBodyAsStream()));
            String readLine;
            while (((readLine = br.readLine()) != null)) {
                response.append(readLine);
            }

        }

    } finally {
        // must release the connection even if an exception occurred
        method.releaseConnection();
        if (br != null) {
            try {
                br.close();
            } catch (Exception ignored) {
            }
        }
    }

    return response.toString();

}

From source file:org.apache.sling.discovery.impl.topology.connector.TopologyRequestValidator.java

/**
 * Trust a message on the client before sending, only if trust is enabled.
 *
 * @param method the method which will have headers set after the call.
 * @param body the body./*from   w ww . j a  v  a  2s . co  m*/
 */
public void trustMessage(HttpMethod method, String body) {
    checkActive();
    if (trustEnabled) {
        String bodyHash = hash("request:" + method.getPath() + ":" + body);
        method.setRequestHeader(HASH_HEADER, bodyHash);
        method.setRequestHeader(SIG_HEADER, createTrustHeader(bodyHash));
    }
}

From source file:org.apache.sling.launchpad.webapp.integrationtest.auth.AuthenticationResponseCodeTest.java

@Test
public void testPreventLoopIncorrectHttpBasicCredentials() throws Exception {

    // assume http and webdav are on the same host + port
    URL url = new URL(HttpTest.HTTP_BASE_URL);
    Credentials defaultcreds = new UsernamePasswordCredentials("garbage", "garbage");
    H.getHttpClient().getState()/*from   w w w . ja v a  2s . c  o m*/
            .setCredentials(new AuthScope(url.getHost(), url.getPort(), AuthScope.ANY_REALM), defaultcreds);

    final String requestUrl = HttpTest.HTTP_BASE_URL + "/junk?param1=1";
    HttpMethod get = new GetMethod(requestUrl);
    get.setRequestHeader("Referer", requestUrl);
    get.setRequestHeader("User-Agent", "Mozilla/5.0 Sling Integration Test");
    int status = H.getHttpClient().executeMethod(get);
    assertEquals(HttpServletResponse.SC_UNAUTHORIZED, status);
}