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

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

Introduction

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

Prototype

public abstract Header getRequestHeader(String paramString);

Source Link

Usage

From source file:org.mule.transport.http.HttpConnector.java

protected void setupClientAuthorization(MuleEvent event, HttpMethod httpMethod, HttpClient client,
        ImmutableEndpoint endpoint) throws UnsupportedEncodingException {
    httpMethod.setDoAuthentication(true);
    client.getParams().setAuthenticationPreemptive(true);

    if (event != null && event.getCredentials() != null) {
        MuleMessage msg = event.getMessage();
        String authScopeHost = msg.getOutboundProperty(HTTP_PREFIX + "auth.scope.host",
                event.getMessageSourceURI().getHost());
        int authScopePort = msg.getOutboundProperty(HTTP_PREFIX + "auth.scope.port",
                event.getMessageSourceURI().getPort());
        String authScopeRealm = msg.getOutboundProperty(HTTP_PREFIX + "auth.scope.realm", AuthScope.ANY_REALM);
        String authScopeScheme = msg.getOutboundProperty(HTTP_PREFIX + "auth.scope.scheme",
                AuthScope.ANY_SCHEME);//  w w w  .ja  va2  s.  c  om
        client.getState().setCredentials(
                new AuthScope(authScopeHost, authScopePort, authScopeRealm, authScopeScheme),
                new UsernamePasswordCredentials(event.getCredentials().getUsername(),
                        new String(event.getCredentials().getPassword())));
    } else if (endpoint.getEndpointURI().getUserInfo() != null
            && endpoint.getProperty(HttpConstants.HEADER_AUTHORIZATION) == null) {
        // Add User Creds
        StringBuffer header = new StringBuffer(128);
        header.append("Basic ");
        header.append(new String(
                Base64.encodeBase64(endpoint.getEndpointURI().getUserInfo().getBytes(endpoint.getEncoding()))));
        httpMethod.addRequestHeader(HttpConstants.HEADER_AUTHORIZATION, header.toString());
    }
    //TODO MULE-4501 this sohuld be removed and handled only in the ObjectToHttpRequest transformer
    else if (event != null && event.getMessage().getOutboundProperty(HttpConstants.HEADER_AUTHORIZATION) != null
            && httpMethod.getRequestHeader(HttpConstants.HEADER_AUTHORIZATION) == null) {
        String auth = event.getMessage().getOutboundProperty(HttpConstants.HEADER_AUTHORIZATION);
        httpMethod.addRequestHeader(HttpConstants.HEADER_AUTHORIZATION, auth);
    } else {
        // don't use preemptive if there are no credentials to send
        client.getParams().setAuthenticationPreemptive(false);
    }
}

From source file:org.mule.transport.http.transformers.ObjectToHttpClientMethodRequestTestCase.java

public void testPostMethod() throws Exception {
    final MuleMessage message = setupRequestContext("http://localhost:8080/services",
            HttpConstants.METHOD_POST);/* w w  w.ja  va  2 s.  com*/
    final String contentType = "text/plain";

    message.setPayload("I'm a payload");
    message.setInvocationProperty(HttpConstants.HEADER_CONTENT_TYPE, contentType);

    final ObjectToHttpClientMethodRequest transformer = createTransformer();
    final Object response = transformer.transform(message);

    assertTrue(response instanceof PostMethod);
    final HttpMethod httpMethod = (HttpMethod) response;
    assertEquals(null, httpMethod.getQueryString());

    assertEquals(contentType, httpMethod.getRequestHeader(HttpConstants.HEADER_CONTENT_TYPE).getValue());
}

From source file:org.mule.transport.http.transformers.ObjectToHttpClientMethodRequestTestCase.java

public void testPutMethod() throws Exception {
    final MuleMessage message = setupRequestContext("http://localhost:8080/services", HttpConstants.METHOD_PUT);
    final String contentType = "text/plain";

    message.setPayload("I'm a payload");
    message.setInvocationProperty(HttpConstants.HEADER_CONTENT_TYPE, contentType);

    final ObjectToHttpClientMethodRequest transformer = createTransformer();
    final Object response = transformer.transform(message);

    assertTrue(response instanceof PutMethod);
    final HttpMethod httpMethod = (HttpMethod) response;
    assertEquals(null, httpMethod.getQueryString());

    assertEquals(contentType, httpMethod.getRequestHeader(HttpConstants.HEADER_CONTENT_TYPE).getValue());
}

From source file:org.mule.transport.legstar.http.LegstarHttpConnector.java

/** 
 * {@inheritDoc}/*from  w  w w  .  j a  v  a  2s .c om*/
 * We override this method from HttpConnector in order to provide basic
 * authentication using the host credentials setup at the connector level
 * or passed as message properties. We do that only if authentication was not setup
 * any other way.
 * 
 * */
protected void setupClientAuthorization(final MuleEvent event, final HttpMethod httpMethod,
        final HttpClient client, final ImmutableEndpoint endpoint) throws UnsupportedEncodingException {
    /* give HttpConnector a chance to setup security*/
    super.setupClientAuthorization(event, httpMethod, client, endpoint);
    HostCredentials hostCredentials = getHostCredentials(event.getMessage());
    if (httpMethod.getRequestHeader(HttpConstants.HEADER_AUTHORIZATION) == null
            && hostCredentials.getUserInfo() != null) {
        if (_log.isDebugEnabled()) {
            _log.debug("adding security header " + hostCredentials.toString());
        }
        StringBuffer header = new StringBuffer(128);
        header.append("Basic ");
        header.append(new String(
                Base64.encodeBase64(hostCredentials.getUserInfo().getBytes(endpoint.getEncoding()))));
        httpMethod.addRequestHeader(HttpConstants.HEADER_AUTHORIZATION, header.toString());
    }
}

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

private synchronized Document doRequest(HttpMethod hm) {
    Document xml = null;/* ww  w . ja v a  2  s  .c  om*/
    try {
        int ret = hc.executeMethod(hm);
        Header[] hs = hm.getResponseHeaders();
        for (Header h : hs) {
            System.err.println("head[" + h.getName() + "] => " + h.getValue());
        }
        if (ret == HttpStatus.SC_UNAUTHORIZED) {
            UsernamePasswordCredentials upc = new UsernamePasswordCredentials(login, password);
            authenticate = hm.getHostAuthState().getAuthScheme().authenticate(upc, hm);
            return null;
        } else if (ret == HttpStatus.SC_OK || ret == HttpStatus.SC_MULTI_STATUS) {
            InputStream is = hm.getResponseBodyAsStream();
            if (is != null) {
                if ("text/xml".equals(hm.getRequestHeader("Content-Type"))) {
                    xml = DOMUtils.parse(is);
                    DOMUtils.logDom(xml);
                } else {
                    System.out.println(FileUtils.streamString(is, false));
                }
            }
        } else {
            System.err.println("method failed:\n" + hm.getStatusLine() + "\n" + hm.getResponseBodyAsString());
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        hm.releaseConnection();
    }
    return xml;
}

From source file:org.parosproxy.paros.network.HttpSender.java

public int executeMethod(HttpMethod method, HttpState state) throws IOException {
    int responseCode = -1;

    String hostName;/*from  ww w. j ava 2  s  .c o  m*/
    hostName = method.getURI().getHost();
    method.setDoAuthentication(true);
    HostConfiguration hc = null;

    HttpClient requestClient;
    if (param.isUseProxy(hostName)) {
        requestClient = clientViaProxy;

    } else {
        // ZAP: use custom client on upgrade connection and on event-source data type
        Header connectionHeader = method.getRequestHeader("connection");
        boolean isUpgrade = connectionHeader != null
                && connectionHeader.getValue().toLowerCase().contains("upgrade");

        // ZAP: try to apply original handling of ParosProxy
        requestClient = client;
        if (isUpgrade) {
            // Unless upgrade, when using another client that allows us to expose the socket
            // connection.
            requestClient = new HttpClient(new ZapHttpConnectionManager());
        }
    }

    if (this.initiator == CHECK_FOR_UPDATES_INITIATOR) {
        // Use the 'strict' SSLConnector, ie one that performs all the usual cert checks
        // The 'standard' one 'trusts' everything
        // This is to ensure that all 'check-for update' calls are made to the expected https urls
        // without this is would be possible to intercept and change the response which could result
        // in the user downloading and installing a malicious add-on
        hc = new HostConfiguration() {
            @Override
            public synchronized void setHost(URI uri) {
                try {
                    setHost(new HttpHost(uri.getHost(), uri.getPort(), getProtocol()));
                } catch (URIException e) {
                    throw new IllegalArgumentException(e.toString());
                }
            };
        };

        hc.setHost(hostName, method.getURI().getPort(),
                new Protocol("https", (ProtocolSocketFactory) new SSLConnector(false), 443));
        if (param.isUseProxy(hostName)) {
            hc.setProxyHost(new ProxyHost(param.getProxyChainName(), param.getProxyChainPort()));
            if (param.isUseProxyChainAuth()) {
                requestClient.getState().setProxyCredentials(getAuthScope(param), getNTCredentials(param));
            }
        }
    }

    // ZAP: Check if a custom state is being used
    if (state != null) {
        // Make sure cookies are enabled
        method.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
    }
    responseCode = requestClient.executeMethod(hc, method, state);

    return responseCode;
}