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

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

Introduction

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

Prototype

public abstract void addRequestHeader(String paramString1, String paramString2);

Source Link

Usage

From source file:org.alfresco.repo.sharepoint.auth.VtiExternalAuthTest.java

public void testExternalAuthNegative() throws HttpException, IOException {
    childApplicationContextManager = (DefaultChildApplicationContextManager) ctx.getBean("Authentication");
    childApplicationContextManager.stop();
    childApplicationContextManager.setProperty("chain", "alfrescoNtlm1:alfrescoNtlm");
    childApplicationContextFactory = getChildApplicationContextFactory(childApplicationContextManager,
            "alfrescoNtlm1");

    String loginURL = "http://localhost:7070/alfresco/";
    HttpClient client = new HttpClient();
    HttpMethod getReq = new GetMethod(loginURL);
    getReq.addRequestHeader("X-Alfresco-Remote-User", "admin");
    int statusCode = client.executeMethod(getReq);
    assertEquals(/*from w w w .j a  v a  2  s. c o m*/
            "sharepoint module should reject external auth if there is no external authentication in chain",
            401, statusCode);
}

From source file:org.apache.abdera.ext.wsse.WSSEAuthScheme.java

public String authenticate(Credentials credentials, HttpMethod method) throws AuthenticationException {
    if (credentials instanceof UsernamePasswordCredentials) {
        UsernamePasswordCredentials creds = (UsernamePasswordCredentials) credentials;
        AtomDate now = new AtomDate(new Date());
        String nonce = generateNonce();
        String digest = generatePasswordDigest(creds.getPassword(), nonce, now);
        String username = creds.getUserName();

        String wsse = "UsernameToken Username=\"" + username + "\", " + "PasswordDigest=\"" + digest + "\", "
                + "Nonce=\"" + nonce + "\", " + "Created=\"" + now.getValue() + "\"";
        if (method != null)
            method.addRequestHeader("X-WSSE", wsse);
        return "WSSE profile=\"UsernameToken\"";
    } else {/*from   w w  w.j  a  v  a  2 s . co m*/
        return null;
    }
}

From source file:org.apache.abdera.protocol.client.util.MethodHelper.java

public static HttpMethod createMethod(String method, String uri, RequestEntity entity, RequestOptions options) {
    if (method == null)
        return null;
    Method m = Method.fromString(method);
    Method actual = null;/*from  w  w  w.  j  a  v  a  2  s .co m*/
    HttpMethod httpMethod = null;
    if (options.isUsePostOverride()) {
        if (m.equals(Method.PUT)) {
            actual = m;
        } else if (m.equals(Method.DELETE)) {
            actual = m;
        }
        if (actual != null)
            m = Method.POST;
    }
    switch (m) {
    case GET:
        httpMethod = new GetMethod(uri);
        break;
    case POST:
        httpMethod = getMethod(new PostMethod(uri), entity);
        break;
    case PUT:
        httpMethod = getMethod(new PutMethod(uri), entity);
        break;
    case DELETE:
        httpMethod = new DeleteMethod(uri);
        break;
    case HEAD:
        httpMethod = new HeadMethod(uri);
        break;
    case OPTIONS:
        httpMethod = new OptionsMethod(uri);
        break;
    case TRACE:
        httpMethod = new TraceMethod(uri);
        break;
    default:
        httpMethod = getMethod(new ExtensionMethod(method, uri), entity);
    }
    if (actual != null) {
        httpMethod.addRequestHeader("X-HTTP-Method-Override", actual.name());
    }
    initHeaders(options, httpMethod);

    // by default use expect-continue is enabled on the client
    // only disable if explicitly disabled
    if (!options.isUseExpectContinue())
        httpMethod.getParams().setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE, false);

    // should we follow redirects, default is true
    if (!(httpMethod instanceof EntityEnclosingMethod))
        httpMethod.setFollowRedirects(options.isFollowRedirects());

    return httpMethod;
}

From source file:org.apache.abdera.protocol.client.util.MethodHelper.java

private static void initHeaders(RequestOptions options, HttpMethod method) {
    String[] headers = options.getHeaderNames();
    for (String header : headers) {
        Object[] values = options.getHeaders(header);
        for (Object value : values) {
            method.addRequestHeader(header, value.toString());
        }/* w  w  w.  j  a v  a  2 s. c om*/
    }
    String cc = options.getCacheControl();
    if (cc != null && cc.length() != 0)
        method.setRequestHeader("Cache-Control", cc);
    if (options.getAuthorization() != null)
        method.setDoAuthentication(false);
}

From source file:org.apache.axis2.transport.http.AbstractHTTPSender.java

protected void executeMethod(HttpClient httpClient, MessageContext msgContext, URL url, HttpMethod method)
        throws IOException {
    HostConfiguration config = this.getHostConfiguration(httpClient, msgContext, url);

    // set the custom headers, if available
    addCustomHeaders(method, msgContext);

    // add compression headers if needed
    if (msgContext.isPropertyTrue(HTTPConstants.MC_ACCEPT_GZIP)) {
        method.addRequestHeader(HTTPConstants.HEADER_ACCEPT_ENCODING, HTTPConstants.COMPRESSION_GZIP);
    }/*from  www  . j av  a 2  s. com*/

    if (msgContext.isPropertyTrue(HTTPConstants.MC_GZIP_REQUEST)) {
        method.addRequestHeader(HTTPConstants.HEADER_CONTENT_ENCODING, HTTPConstants.COMPRESSION_GZIP);
    }

    if (msgContext.getProperty(HTTPConstants.HTTP_METHOD_PARAMS) != null) {
        HttpMethodParams params = (HttpMethodParams) msgContext.getProperty(HTTPConstants.HTTP_METHOD_PARAMS);
        method.setParams(params);
    }

    String cookiePolicy = (String) msgContext.getProperty(HTTPConstants.COOKIE_POLICY);
    if (cookiePolicy != null) {
        method.getParams().setCookiePolicy(cookiePolicy);
    }
    HttpState httpState = (HttpState) msgContext.getProperty(HTTPConstants.CACHED_HTTP_STATE);

    setTimeouts(msgContext, method);

    httpClient.executeMethod(config, method, httpState);
}

From source file:org.apache.camel.component.http.HttpProducer.java

public void process(Exchange exchange) throws Exception {
    // if we bridge endpoint then we need to skip matching headers with the HTTP_QUERY to avoid sending
    // duplicated headers to the receiver, so use this skipRequestHeaders as the list of headers to skip
    Map<String, Object> skipRequestHeaders = null;

    if (getEndpoint().isBridgeEndpoint()) {
        exchange.setProperty(Exchange.SKIP_GZIP_ENCODING, Boolean.TRUE);
        String queryString = exchange.getIn().getHeader(Exchange.HTTP_QUERY, String.class);
        if (queryString != null) {
            skipRequestHeaders = URISupport.parseQuery(queryString);
        }//w w w.  j  a v a  2 s  .c  o m
        // Need to remove the Host key as it should be not used 
        exchange.getIn().getHeaders().remove("host");
    }
    HttpMethod method = createMethod(exchange);
    Message in = exchange.getIn();
    String httpProtocolVersion = in.getHeader(Exchange.HTTP_PROTOCOL_VERSION, String.class);
    if (httpProtocolVersion != null) {
        // set the HTTP protocol version
        HttpMethodParams params = method.getParams();
        params.setVersion(HttpVersion.parse(httpProtocolVersion));
    }

    HeaderFilterStrategy strategy = getEndpoint().getHeaderFilterStrategy();

    // propagate headers as HTTP headers
    for (Map.Entry<String, Object> entry : in.getHeaders().entrySet()) {
        String key = entry.getKey();
        Object headerValue = in.getHeader(key);

        if (headerValue != null) {
            // use an iterator as there can be multiple values. (must not use a delimiter, and allow empty values)
            final Iterator<?> it = ObjectHelper.createIterator(headerValue, null, true);

            // the value to add as request header
            final List<String> values = new ArrayList<String>();

            // if its a multi value then check each value if we can add it and for multi values they
            // should be combined into a single value
            while (it.hasNext()) {
                String value = exchange.getContext().getTypeConverter().convertTo(String.class, it.next());

                // we should not add headers for the parameters in the uri if we bridge the endpoint
                // as then we would duplicate headers on both the endpoint uri, and in HTTP headers as well
                if (skipRequestHeaders != null && skipRequestHeaders.containsKey(key)) {
                    continue;
                }
                if (value != null && strategy != null
                        && !strategy.applyFilterToCamelHeaders(key, value, exchange)) {
                    values.add(value);
                }
            }

            // add the value(s) as a http request header
            if (values.size() > 0) {
                // use the default toString of a ArrayList to create in the form [xxx, yyy]
                // if multi valued, for a single value, then just output the value as is
                String s = values.size() > 1 ? values.toString() : values.get(0);
                method.addRequestHeader(key, s);
            }
        }
    }

    // lets store the result in the output message.
    try {
        if (LOG.isDebugEnabled()) {
            LOG.debug("Executing http {} method: {}", method.getName(), method.getURI().toString());
        }
        int responseCode = executeMethod(method);
        LOG.debug("Http responseCode: {}", responseCode);

        if (!throwException) {
            // if we do not use failed exception then populate response for all response codes
            populateResponse(exchange, method, in, strategy, responseCode);
        } else {
            if (responseCode >= 100 && responseCode < 300) {
                // only populate response for OK response
                populateResponse(exchange, method, in, strategy, responseCode);
            } else {
                // operation failed so populate exception to throw
                throw populateHttpOperationFailedException(exchange, method, responseCode);
            }
        }
    } finally {
        method.releaseConnection();
    }
}

From source file:org.apache.camel.component.jetty.EnableCORSTest.java

@Test
public void testCORSdisabled() throws Exception {
    HttpClient httpclient = new HttpClient();
    HttpMethod httpMethod = new GetMethod("http://localhost:" + getPort() + "/test1");
    httpMethod.addRequestHeader("Origin", "http://localhost:9000");
    httpMethod.addRequestHeader("Referer", "http://localhost:9000");

    int status = httpclient.executeMethod(httpMethod);

    assertEquals("Get a wrong response status", 200, status);

    Header responseHeader = httpMethod.getResponseHeader("Access-Control-Allow-Credentials");
    assertNull("Access-Control-Allow-Credentials HEADER should not be set", responseHeader);
}

From source file:org.apache.camel.component.jetty.EnableCORSTest.java

@Test
public void testCORSenabled() throws Exception {
    HttpClient httpclient = new HttpClient();
    HttpMethod httpMethod = new GetMethod("http://localhost:" + getPort2() + "/test2");
    httpMethod.addRequestHeader("Origin", "http://localhost:9000");
    httpMethod.addRequestHeader("Referer", "http://localhost:9000");

    int status = httpclient.executeMethod(httpMethod);

    assertEquals("Get a wrong response status", 200, status);

    Header responseHeader = httpMethod.getResponseHeader("Access-Control-Allow-Credentials");
    assertTrue("CORS not enabled", Boolean.valueOf(responseHeader.getValue()));

}

From source file:org.apache.cocoon.transformation.SparqlTransformer.java

private void executeRequest(String url, String method, Map httpHeaders, SourceParameters requestParameters)
        throws ProcessingException, IOException, SAXException {
    HttpClient httpclient = new HttpClient();
    if (System.getProperty("http.proxyHost") != null) {
        // getLogger().warn("PROXY: "+System.getProperty("http.proxyHost"));
        String nonProxyHostsRE = System.getProperty("http.nonProxyHosts", "");
        if (nonProxyHostsRE.length() > 0) {
            String[] pHosts = nonProxyHostsRE.replaceAll("\\.", "\\\\.").replaceAll("\\*", ".*").split("\\|");
            nonProxyHostsRE = "";
            for (String pHost : pHosts) {
                nonProxyHostsRE += "|(^https?://" + pHost + ".*$)";
            }/* w w  w  . j  a va  2s  .c o  m*/
            nonProxyHostsRE = nonProxyHostsRE.substring(1);
        }
        if (nonProxyHostsRE.length() == 0 || !url.matches(nonProxyHostsRE)) {
            try {
                HostConfiguration hostConfiguration = httpclient.getHostConfiguration();
                hostConfiguration.setProxy(System.getProperty("http.proxyHost"),
                        Integer.parseInt(System.getProperty("http.proxyPort", "80")));
                httpclient.setHostConfiguration(hostConfiguration);
            } catch (Exception e) {
                throw new ProcessingException("Cannot set proxy!", e);
            }
        }
    }
    // Make the HttpMethod.
    HttpMethod httpMethod = null;
    // Do not use empty query parameter.
    if (requestParameters.getParameter(parameterName).trim().equals("")) {
        requestParameters.removeParameter(parameterName);
    }
    // Instantiate different HTTP methods.
    if ("GET".equalsIgnoreCase(method)) {
        httpMethod = new GetMethod(url);
        if (requestParameters.getEncodedQueryString() != null) {
            httpMethod.setQueryString(
                    requestParameters.getEncodedQueryString().replace("\"", "%22")); /* Also escape '"' */
        } else {
            httpMethod.setQueryString("");
        }
    } else if ("POST".equalsIgnoreCase(method)) {
        PostMethod httpPostMethod = new PostMethod(url);
        if (httpHeaders.containsKey(HTTP_CONTENT_TYPE) && ((String) httpHeaders.get(HTTP_CONTENT_TYPE))
                .startsWith("application/x-www-form-urlencoded")) {
            // Encode parameters in POST body.
            Iterator parNames = requestParameters.getParameterNames();
            while (parNames.hasNext()) {
                String parName = (String) parNames.next();
                httpPostMethod.addParameter(parName, requestParameters.getParameter(parName));
            }
        } else {
            // Use query parameter as POST body
            httpPostMethod.setRequestBody(requestParameters.getParameter(parameterName));
            // Add other parameters to query string
            requestParameters.removeParameter(parameterName);
            if (requestParameters.getEncodedQueryString() != null) {
                httpPostMethod.setQueryString(
                        requestParameters.getEncodedQueryString().replace("\"", "%22")); /* Also escape '"' */
            } else {
                httpPostMethod.setQueryString("");
            }
        }
        httpMethod = httpPostMethod;
    } else if ("PUT".equalsIgnoreCase(method)) {
        PutMethod httpPutMethod = new PutMethod(url);
        httpPutMethod.setRequestBody(requestParameters.getParameter(parameterName));
        requestParameters.removeParameter(parameterName);
        httpPutMethod.setQueryString(requestParameters.getEncodedQueryString());
        httpMethod = httpPutMethod;
    } else if ("DELETE".equalsIgnoreCase(method)) {
        httpMethod = new DeleteMethod(url);
        httpMethod.setQueryString(requestParameters.getEncodedQueryString());
    } else {
        throw new ProcessingException("Unsupported method: " + method);
    }
    // Authentication (optional).
    if (credentials != null && credentials.length() > 0) {
        String[] unpw = credentials.split("\t");
        httpclient.getParams().setAuthenticationPreemptive(true);
        httpclient.getState().setCredentials(new AuthScope(httpMethod.getURI().getHost(),
                httpMethod.getURI().getPort(), AuthScope.ANY_REALM),
                new UsernamePasswordCredentials(unpw[0], unpw[1]));
    }
    // Add request headers.
    Iterator headers = httpHeaders.entrySet().iterator();
    while (headers.hasNext()) {
        Map.Entry header = (Map.Entry) headers.next();
        httpMethod.addRequestHeader((String) header.getKey(), (String) header.getValue());
    }
    // Declare some variables before the try-block.
    XMLizer xmlizer = null;
    try {
        // Execute the request.
        int responseCode;
        responseCode = httpclient.executeMethod(httpMethod);
        // Handle errors, if any.
        if (responseCode < 200 || responseCode >= 300) {
            if (showErrors) {
                AttributesImpl attrs = new AttributesImpl();
                attrs.addCDATAAttribute("status", "" + responseCode);
                xmlConsumer.startElement(SPARQL_NAMESPACE_URI, "error", "sparql:error", attrs);
                String responseBody = httpMethod.getStatusText(); //httpMethod.getResponseBodyAsString();
                xmlConsumer.characters(responseBody.toCharArray(), 0, responseBody.length());
                xmlConsumer.endElement(SPARQL_NAMESPACE_URI, "error", "sparql:error");
                return; // Not a nice, but quick and dirty way to end.
            } else {
                throw new ProcessingException("Received HTTP status code " + responseCode + " "
                        + httpMethod.getStatusText() + ":\n" + httpMethod.getResponseBodyAsString());
            }
        }
        // Parse the response
        if (responseCode == 204) { // No content.
            String statusLine = httpMethod.getStatusLine().toString();
            xmlConsumer.startElement(SPARQL_NAMESPACE_URI, "result", "sparql:result", EMPTY_ATTRIBUTES);
            xmlConsumer.characters(statusLine.toCharArray(), 0, statusLine.length());
            xmlConsumer.endElement(SPARQL_NAMESPACE_URI, "result", "sparql:result");
        } else if (parse.equalsIgnoreCase("xml")) {
            InputStream responseBodyStream = httpMethod.getResponseBodyAsStream();
            xmlizer = (XMLizer) manager.lookup(XMLizer.ROLE);
            xmlizer.toSAX(responseBodyStream, "text/xml", httpMethod.getURI().toString(),
                    new IncludeXMLConsumer(xmlConsumer));
            responseBodyStream.close();
        } else if (parse.equalsIgnoreCase("text")) {
            xmlConsumer.startElement(SPARQL_NAMESPACE_URI, "result", "sparql:result", EMPTY_ATTRIBUTES);
            String responseBody = httpMethod.getResponseBodyAsString();
            xmlConsumer.characters(responseBody.toCharArray(), 0, responseBody.length());
            xmlConsumer.endElement(SPARQL_NAMESPACE_URI, "result", "sparql:result");
        } else {
            throw new ProcessingException("Unknown parse type: " + parse);
        }
    } catch (ServiceException e) {
        throw new ProcessingException("Cannot find the right XMLizer for " + XMLizer.ROLE, e);
    } finally {
        if (xmlizer != null)
            manager.release((Component) xmlizer);
        httpMethod.releaseConnection();
    }
}

From source file:org.apache.commons.httpclient.demo.GetOtherUrlDate.java

public static void main(String[] args) {
    //GetOtherUrlDate getotherurldate = new GetOtherUrlDate();
    HttpClient hc = new HttpClient();
    ////from w w w.  j  av  a 2s  .  c om
    //hc.getHostConfiguration().setProxy("90.0.12.21",808);

    HttpMethod hm = new GetMethod("http://www.sina.com.cn");
    hm.addRequestHeader("Content-Type", "text/html;charset=utf-8"); //

    int statusCode = -1;
    byte[] result = null;

    try {
        statusCode = hc.executeMethod(hm);
        if (statusCode != HttpStatus.SC_OK) { //
            System.out.println("get failure!");
            return;
        }

        if (hm.getResponseBody() != null) { //
            result = hm.getResponseBody(); //hm.getStatusLine()DDhttp
        }

    } catch (HttpException e1) {
        e1.printStackTrace();
    } catch (java.io.IOException e2) {
        e2.printStackTrace();
    }

    hm.releaseConnection();
    String data = null;

    if (result != null) {
        try {
            //data = new String(result, "UTF-8"); //
            data = new String(result, "GB2312"); //
        } catch (UnsupportedEncodingException ex) {
            ex.printStackTrace();
        }
        //System.out.println(data.substring(0, 500)); //
        int begin = data.indexOf("product"); //

        System.out.println("===============================");
        System.out.println("product:" + begin);
        System.out.println("===============================");

        if (begin > -1) { //1000
            System.out.println(data.substring(begin, begin + 1000));
            //System.out.println(Strings.convertHTML(data.substring(begin,begin + 1000)));
        }
    }
}