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.methodize.nntprss.feed.Channel.java

/**
 * Simple channel validation - ensures URL
 * is valid, XML document is returned, and
 * document has an rss root element with a 
 * version, or rdf root element, //from   w  w  w  .ja va 2 s .c o  m
 */
public static boolean isValid(URL url) throws HttpUserException {
    boolean valid = false;
    try {
        //         System.setProperty("networkaddress.cache.ttl", "0");

        HttpClient client = new HttpClient();
        ChannelManager.getChannelManager().configureHttpClient(client);
        if (url.getUserInfo() != null) {
            client.getState().setCredentials(null, null,
                    new UsernamePasswordCredentials(URLDecoder.decode(url.getUserInfo())));
        }

        String urlString = url.toString();
        HttpMethod method = null;

        int count = 0;
        HttpResult result = null;
        int statusCode = HttpStatus.SC_OK;
        boolean redirected = false;
        do {
            method = new GetMethod(urlString);
            method.setRequestHeader("User-agent", AppConstants.getUserAgent());
            method.setRequestHeader("Accept-Encoding", "gzip");
            method.setFollowRedirects(false);
            method.setDoAuthentication(true);

            HostConfiguration hostConfiguration = client.getHostConfiguration();
            URI hostURI = new URI(urlString);
            hostConfiguration.setHost(hostURI);

            result = executeHttpRequest(client, hostConfiguration, method);
            statusCode = result.getStatusCode();
            if (statusCode == HttpStatus.SC_MOVED_PERMANENTLY || statusCode == HttpStatus.SC_MOVED_TEMPORARILY
                    || statusCode == HttpStatus.SC_SEE_OTHER
                    || statusCode == HttpStatus.SC_TEMPORARY_REDIRECT) {
                redirected = true;
                // Resolve against current URI - may be a relative URI
                try {
                    urlString = new java.net.URI(urlString).resolve(result.getLocation()).toString();
                } catch (URISyntaxException use) {
                    // Fall back to just using location from result
                    urlString = result.getLocation();
                }
            } else {
                redirected = false;
            }

            //            method.getResponseBody();
            //            method.releaseConnection();
            count++;
        } while (count < 5 && redirected);

        // Only process if ok - if not ok (e.g. not modified), don't do anything
        if (statusCode == HttpStatus.SC_OK) {
            PushbackInputStream pbis = new PushbackInputStream(new ByteArrayInputStream(result.getResponse()),
                    PUSHBACK_BUFFER_SIZE);
            skipBOM(pbis);

            BufferedInputStream bis = new BufferedInputStream(pbis);
            DocumentBuilder db = AppConstants.newDocumentBuilder();
            Document rssDoc = db.parse(bis);
            Element rootElm = rssDoc.getDocumentElement();

            for (int i = 0; i < parsers.length; i++) {
                if (parsers[i].isParsable(rootElm)) {
                    valid = true;
                    break;
                }
            }
        } else if (statusCode == HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED) {
            throw new HttpUserException(statusCode);
        } else if (statusCode == HttpStatus.SC_UNAUTHORIZED) {
            throw new HttpUserException(statusCode);
        }

    } catch (URIException e) {
        e.printStackTrace();
    } catch (ParserConfigurationException e) {
        e.printStackTrace();
    } catch (SAXException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    return valid;
}

From source file:org.mimacom.maven.plugins.liferay.prepare.MultithreadedDownloader.java

private boolean canPartialDownload(HttpMethod method) throws IOException {
    method.setRequestHeader("Range", "bytes=0-1");
    int status = httpClient.executeMethod(method);
    return (status == HttpStatus.SC_PARTIAL_CONTENT);
}

From source file:org.mule.ibeans.module.http.HttpClientMessageRequester2.java

/**
 * Make a specific request to the underlying transport
 *
 * @param timeout the maximum time the operation should block before returning.
 *                The call should return immediately if there is data available. If
 *                no data becomes available before the timeout elapses, null will be
 *                returned/*from   w  ww.ja  v a  2s . c o m*/
 * @return the result of the request wrapped in a MuleMessage object. Null will be
 *         returned if no data was avaialable
 * @throws Exception if the call to the underlying protocal cuases an exception
 */
protected MuleMessage doRequest(long timeout) throws Exception {
    HttpMethod httpMethod = new GetMethod(endpoint.getEndpointURI().getAddress());

    if (endpoint.getProperties().containsKey(HttpConstants.HEADER_AUTHORIZATION)) {
        httpMethod.setDoAuthentication(true);
        client.getParams().setAuthenticationPreemptive(true);
        httpMethod.setRequestHeader(HttpConstants.HEADER_AUTHORIZATION,
                (String) endpoint.getProperty(HttpConstants.HEADER_AUTHORIZATION));
    }

    boolean releaseConn = false;
    try {
        HttpClient client = new HttpClient();

        if (etag != null && checkEtag) {
            httpMethod.setRequestHeader(HttpConstants.HEADER_IF_NONE_MATCH, etag);
        }
        client.executeMethod(httpMethod);

        if (httpMethod.getStatusCode() < 400) {
            MuleMessage message = new HttpMuleMessageFactory(connector.getMuleContext()).create(httpMethod,
                    null /* encoding */);
            etag = message.getInboundProperty(HttpConstants.HEADER_ETAG, null);

            if (httpMethod.getStatusCode() == HttpStatus.SC_OK
                    || (httpMethod.getStatusCode() != HttpStatus.SC_NOT_MODIFIED || !checkEtag)) {
                if (StringUtils.EMPTY.equals(message.getPayload())) {
                    releaseConn = true;
                }
                return message;
            } else {
                //Not modified, we should really cache the whole message and return it
                return new DefaultMuleMessage(NullPayload.getInstance(), getConnector().getMuleContext());
            }
        } else {
            releaseConn = true;
            throw new ReceiveException(
                    HttpMessages.requestFailedWithStatus(httpMethod.getStatusLine().toString()), endpoint,
                    timeout);
        }

    } catch (ReceiveException e) {
        releaseConn = true;
        throw e;
    } catch (Exception e) {
        releaseConn = true;
        throw new ReceiveException(endpoint, timeout, e);
    } finally {
        if (releaseConn) {
            httpMethod.releaseConnection();
        }
    }
}

From source file:org.nunux.poc.portal.ProxyServlet.java

/**
 * Retrieves all of the cookies from the servlet request and sets them on
 * the proxy request/*from w w w. j  a  v  a 2s. 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 setProxyRequestCookies(HttpServletRequest httpServletRequest, HttpMethod httpMethodProxyRequest) {
    // Get an array of all of all the cookies sent by the client
    Cookie[] cookies = httpServletRequest.getCookies();
    if (cookies == null) {
        return;
    }

    if (httpServletRequest.getSession().getAttribute("jsessionid" + this.getProxyHostAndPort()) != null) {
        String jsessionid = (String) httpServletRequest.getSession()
                .getAttribute("jsessionid" + this.getProxyHostAndPort());
        httpMethodProxyRequest.setRequestHeader("Cookie", "JSESSIONID=" + jsessionid);
        debug("redirecting: setting jsessionid: " + jsessionid);
    }

    for (Cookie cookie : cookies) {
        if (!cookie.getName().equalsIgnoreCase("jsessionid")) {
            cookie.setDomain(stringProxyHost);
            cookie.setPath(httpServletRequest.getServletPath());
            httpMethodProxyRequest.setRequestHeader("Cookie",
                    cookie.getName() + "=" + cookie.getValue() + "; Path=" + cookie.getPath());
        }
    }
}

From source file:org.nuxeo.ecm.tokenauth.TestTokenAuthenticationServlet.java

/**
 * Executes the specified HTTP method on the specified HTTP client with a basic authentication header given the
 * specified credentials./*from  w w  w.  ja v  a  2s  . co m*/
 */
protected final int executeGetMethod(HttpClient httpClient, HttpMethod httpMethod, String userName,
        String password) throws HttpException, IOException {

    String authString = userName + ":" + password;
    String basicAuthHeader = "Basic " + new String(Base64.encodeBase64(authString.getBytes()));
    httpMethod.setRequestHeader("Authorization", basicAuthHeader);
    return httpClient.executeMethod(httpMethod);
}

From source file:org.nuxeo.jira.NuxeoServerInfoCollector.java

/**
 * Executes the specified HTTP method on the specified HTTP client with a
 * basic authentication header given the specified credentials.
 *//*from ww w  .j  a v a  2s  .  c o m*/
protected static final int executeGetMethod(HttpClient httpClient, HttpMethod httpMethod, String userName,
        String password) throws HttpException, IOException {

    String authString = userName + ":" + password;
    String basicAuthHeader = "Basic " + new String(Base64.encodeBase64(authString.getBytes()));
    httpMethod.setRequestHeader("Authorization", basicAuthHeader);
    return httpClient.executeMethod(httpMethod);
}

From source file:org.nuxeo.opensocial.shindig.gadgets.NXHttpFetcher.java

/** {@inheritDoc} */
public HttpResponse fetch(HttpRequest request) {
    HttpClient httpClient = new HttpClient();
    HttpMethod httpMethod;
    String methodType = request.getMethod();
    String requestUri = request.getUri().toString();

    ProxyHelper.fillProxy(httpClient, requestUri);

    // true for non-HEAD requests
    boolean requestCompressedContent = true;

    if ("POST".equals(methodType) || "PUT".equals(methodType)) {
        EntityEnclosingMethod enclosingMethod = ("POST".equals(methodType)) ? new PostMethod(requestUri)
                : new PutMethod(requestUri);

        if (request.getPostBodyLength() > 0) {
            enclosingMethod.setRequestEntity(new InputStreamRequestEntity(request.getPostBody()));
            enclosingMethod.setRequestHeader("Content-Length", String.valueOf(request.getPostBodyLength()));
        }//from www .  ja  v a 2  s . c om
        httpMethod = enclosingMethod;
    } else if ("DELETE".equals(methodType)) {
        httpMethod = new DeleteMethod(requestUri);
    } else if ("HEAD".equals(methodType)) {
        httpMethod = new HeadMethod(requestUri);
    } else {
        httpMethod = new GetMethod(requestUri);
    }

    httpMethod.setFollowRedirects(false);
    httpMethod.getParams().setSoTimeout(connectionTimeoutMs);

    if (requestCompressedContent)
        httpMethod.setRequestHeader("Accept-Encoding", "gzip, deflate");

    for (Map.Entry<String, List<String>> entry : request.getHeaders().entrySet()) {
        httpMethod.setRequestHeader(entry.getKey(), StringUtils.join(entry.getValue(), ','));
    }

    try {

        int statusCode = httpClient.executeMethod(httpMethod);

        // Handle redirects manually
        if (request.getFollowRedirects() && ((statusCode == HttpStatus.SC_MOVED_TEMPORARILY)
                || (statusCode == HttpStatus.SC_MOVED_PERMANENTLY) || (statusCode == HttpStatus.SC_SEE_OTHER)
                || (statusCode == HttpStatus.SC_TEMPORARY_REDIRECT))) {

            Header header = httpMethod.getResponseHeader("location");
            if (header != null) {
                String redirectUri = header.getValue();

                if ((redirectUri == null) || (redirectUri.equals(""))) {
                    redirectUri = "/";
                }
                httpMethod.releaseConnection();
                httpMethod = new GetMethod(redirectUri);

                statusCode = httpClient.executeMethod(httpMethod);
            }
        }

        return makeResponse(httpMethod, statusCode);

    } catch (IOException e) {
        if (e instanceof java.net.SocketTimeoutException || e instanceof java.net.SocketException) {
            return HttpResponse.timeout();
        }

        return HttpResponse.error();

    } finally {
        httpMethod.releaseConnection();
    }
}

From source file:org.obm.caldav.client.AbstractPushTest.java

private void appendHeader(HttpMethod hm, ByteArrayOutputStream out) {
    hm.setRequestHeader("Host", "lemurien.tlse.lng:8008");
    hm.setRequestHeader("User-Agent", userAgent);
    hm.setRequestHeader("Accept", "text/xml");
    hm.setRequestHeader("Accept-Charset", "utf-8,*;q=0.1");
    hm.setRequestHeader("Content-Length", "" + out.size());
    hm.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
    hm.setRequestHeader("Depth", "0");
    if (authenticate != null && !"".equals(authenticate)) {
        hm.setRequestHeader("Authorization", authenticate);
    }//from w w w. ja va  2  s . co  m
}

From source file:org.paxle.crawler.http.impl.HttpCrawler.java

/**
 * Initializes the {@link HttpMethod} with common attributes for all requests this crawler
 * initiates./*ww  w .  ja v a2  s. c o m*/
 * <p>
 * Currently the following attributes (represented as HTTP header values in the final request)
 * are set:
 * <ul>
 *   <li>the cookie policy to use ({@link #PROP_COOKIE_POLICY})</li>
 *   <li>
 *     if enabled, content-transformation using <code>compress</code>, <code>gzip</code> and
 *     <code>deflate</code> is supported</li>
 *   </li> 
 * </ul>
 * 
 * @param method the method to set the standard attributes on
 */
private void initRequestMethod(final HttpMethod method) throws URIException {
    method.getParams().setCookiePolicy(
            this.cookiePolicy == null ? CookiePolicy.BROWSER_COMPATIBILITY : this.cookiePolicy);
    if (acceptEncoding && !isHostSettingSet(method.getURI().getHost(), PREF_NO_ENCODING))
        method.setRequestHeader(HTTPHEADER_ACCEPT_ENCODING, "compress, gzip, identity, deflate"); // see RFC 2616, section 14.3

    // set some additional http headers
    if (this.userAgent != null) {
        method.setRequestHeader("User-Agent", this.userAgent);
    }
}

From source file:org.pengyou.client.lib.DavResource.java

/**
 * Generates and adds the "Transaction" header if this method is part of
 * an externally controlled transaction.
 *//*from   www.jav a  2 s .com*/
protected void generateTransactionHeader(HttpMethod method) {
    if (this.client == null || method == null)
        return;

    WebdavState state = (WebdavState) this.client.getState();
    String txHandle = state.getTransactionHandle();
    if (txHandle != null) {
        method.setRequestHeader("Transaction", "<" + txHandle + ">");
    }
}