Example usage for org.apache.commons.httpclient HttpClient getState

List of usage examples for org.apache.commons.httpclient HttpClient getState

Introduction

In this page you can find the example usage for org.apache.commons.httpclient HttpClient getState.

Prototype

public HttpState getState()

Source Link

Usage

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

public void configure(MessageContext messageContext, HttpClient httpClient, HostConfiguration config)
        throws AxisFault {

    //        <parameter name="Proxy">
    //              <Configuration>
    //                     <ProxyHost>example.org</ProxyHost>
    //                     <ProxyPort>5678</ProxyPort>
    //                     <ProxyUser>EXAMPLE\saminda</ProxyUser>
    //                     <ProxyPassword>ppp</ProxyPassword>
    //              </Configuration>
    //        </parameter>
    Credentials proxyCred = null;/*from  ww  w . j a va  2s .co  m*/

    //Getting configuration values from Axis2.xml
    Parameter param = messageContext.getConfigurationContext().getAxisConfiguration().getParameter(ATTR_PROXY);

    if (param != null) {
        OMElement configurationEle = param.getParameterElement().getFirstElement();
        if (configurationEle == null) {
            throw new AxisFault(ProxyConfiguration.class.getName() + " Configuration element is missing");
        }

        OMElement proxyHostEle = configurationEle.getFirstChildWithName(new QName(PROXY_HOST_ELEMENT));
        OMElement proxyPortEle = configurationEle.getFirstChildWithName(new QName(PROXY_PORT_ELEMENT));
        OMElement proxyUserEle = configurationEle.getFirstChildWithName(new QName(PROXY_USER_ELEMENT));
        OMElement proxyPasswordEle = configurationEle.getFirstChildWithName(new QName(PROXY_PASSWORD_ELEMENT));

        if (proxyHostEle == null) {
            throw new AxisFault(ProxyConfiguration.class.getName() + " ProxyHost element is missing");
        }
        String text = proxyHostEle.getText();
        if (text == null) {
            throw new AxisFault(ProxyConfiguration.class.getName() + " ProxyHost's value is missing");
        }

        this.setProxyHost(text);

        if (proxyPortEle != null) {
            this.setProxyPort(Integer.parseInt(proxyPortEle.getText()));
        }

        if (proxyUserEle != null) {
            this.setProxyUser(proxyUserEle.getText());
        }

        if (proxyPasswordEle != null) {
            this.setProxyPassword(proxyPasswordEle.getText());
        }

        if (this.getProxyUser() == null && this.getProxyUser() == null) {
            proxyCred = new UsernamePasswordCredentials("", "");
        } else {
            proxyCred = new UsernamePasswordCredentials(this.getProxyUser(), this.getProxyPassword());
        }

        // if the username is in the form "DOMAIN\\user"
        // then use NTCredentials instead.
        if (this.getProxyUser() != null) {
            int domainIndex = this.getProxyUser().indexOf("\\");
            if (domainIndex > 0) {
                String domain = this.getProxyUser().substring(0, domainIndex);
                if (this.getProxyUser().length() > domainIndex + 1) {
                    String user = this.getProxyUser().substring(domainIndex + 1);
                    proxyCred = new NTCredentials(user, this.getProxyPassword(), this.getProxyHost(), domain);
                }
            }
        }
    }

    // Overide the property setting in runtime.
    HttpTransportProperties.ProxyProperties proxyProperties = (HttpTransportProperties.ProxyProperties) messageContext
            .getProperty(HTTPConstants.PROXY);

    if (proxyProperties != null) {
        String host = proxyProperties.getProxyHostName();
        if (host == null || host.length() == 0) {
            throw new AxisFault(ProxyConfiguration.class.getName()
                    + " Proxy host is not available. Host is a MUST parameter");

        } else {
            this.setProxyHost(host);
        }

        this.setProxyPort(proxyProperties.getProxyPort());

        //Setting credentials

        String userName = proxyProperties.getUserName();
        String password = proxyProperties.getPassWord();
        String domain = proxyProperties.getDomain();

        if (userName == null && password == null) {
            proxyCred = new UsernamePasswordCredentials("", "");
        } else {
            proxyCred = new UsernamePasswordCredentials(userName, password);
        }

        if (userName != null && password != null && domain != null) {
            proxyCred = new NTCredentials(userName, password, host, domain);
        }

    }

    //Using Java Networking Properties

    String host = System.getProperty(HTTP_PROXY_HOST);
    if (host != null) {
        this.setProxyHost(host);
        proxyCred = new UsernamePasswordCredentials("", "");
    }

    String port = System.getProperty(HTTP_PROXY_PORT);

    if (port != null) {
        this.setProxyPort(Integer.parseInt(port));
    }

    if (proxyCred == null) {
        throw new AxisFault(ProxyConfiguration.class.getName() + " Minimum proxy credentials are not set");
    }
    httpClient.getState().setProxyCredentials(AuthScope.ANY, proxyCred);
    config.setProxy(this.getProxyHost(), this.getProxyPort());
}

From source file:org.apache.axis2.transport.http.util.HTTPProxyConfigurationUtil.java

/**
 * Configure HTTP Proxy settings of commons-httpclient HostConfiguration. Proxy settings can be get from
 * axis2.xml, Java proxy settings or can be override through property in message context.
 * <p/>//from  w  w w  .  j  a  va 2 s.co m
 * HTTP Proxy setting element format:
 * <parameter name="Proxy">
 * <Configuration>
 * <ProxyHost>example.org</ProxyHost>
 * <ProxyPort>3128</ProxyPort>
 * <ProxyUser>EXAMPLE/John</ProxyUser>
 * <ProxyPassword>password</ProxyPassword>
 * <Configuration>
 * <parameter>
 *
 * @param messageContext in message context for
 * @param httpClient     commons-httpclient instance
 * @param config         commons-httpclient HostConfiguration
 * @throws AxisFault if Proxy settings are invalid
 */
public static void configure(MessageContext messageContext, HttpClient httpClient, HostConfiguration config)
        throws AxisFault {

    Credentials proxyCredentials = null;
    String proxyHost = null;
    String nonProxyHosts = null;
    Integer proxyPort = -1;
    String proxyUser = null;
    String proxyPassword = null;

    //Getting configuration values from Axis2.xml
    Parameter proxySettingsFromAxisConfig = messageContext.getConfigurationContext().getAxisConfiguration()
            .getParameter(ATTR_PROXY);
    if (proxySettingsFromAxisConfig != null) {
        OMElement proxyConfiguration = getProxyConfigurationElement(proxySettingsFromAxisConfig);
        proxyHost = getProxyHost(proxyConfiguration);
        proxyPort = getProxyPort(proxyConfiguration);
        proxyUser = getProxyUser(proxyConfiguration);
        proxyPassword = getProxyPassword(proxyConfiguration);
        if (proxyUser != null) {
            if (proxyPassword == null) {
                proxyPassword = "";
            }
            int proxyUserDomainIndex = proxyUser.indexOf("\\");
            if (proxyUserDomainIndex > 0) {
                String domain = proxyUser.substring(0, proxyUserDomainIndex);
                if (proxyUser.length() > proxyUserDomainIndex + 1) {
                    String user = proxyUser.substring(proxyUserDomainIndex + 1);
                    proxyCredentials = new NTCredentials(user, proxyPassword, proxyHost, domain);
                }
            }
            proxyCredentials = new UsernamePasswordCredentials(proxyUser, proxyPassword);
        }

    }

    // If there is runtime proxy settings, these settings will override settings from axis2.xml
    HttpTransportProperties.ProxyProperties proxyProperties = (HttpTransportProperties.ProxyProperties) messageContext
            .getProperty(HTTPConstants.PROXY);
    if (proxyProperties != null) {
        String proxyHostProp = proxyProperties.getProxyHostName();
        if (proxyHostProp == null || proxyHostProp.length() <= 0) {
            throw new AxisFault("HTTP Proxy host is not available. Host is a MUST parameter");
        } else {
            proxyHost = proxyHostProp;
        }
        proxyPort = proxyProperties.getProxyPort();

        // Overriding credentials
        String userName = proxyProperties.getUserName();
        String password = proxyProperties.getPassWord();
        String domain = proxyProperties.getDomain();

        if (userName != null && password != null && domain != null) {
            proxyCredentials = new NTCredentials(userName, password, proxyHost, domain);
        } else if (userName != null && domain == null) {
            proxyCredentials = new UsernamePasswordCredentials(userName, password);
        }

    }

    // Overriding proxy settings if proxy is available from JVM settings
    String host = System.getProperty(HTTP_PROXY_HOST);
    if (host != null) {
        proxyHost = host;
    }

    String port = System.getProperty(HTTP_PROXY_PORT);
    if (port != null) {
        proxyPort = Integer.parseInt(port);
    }

    if (proxyCredentials != null) {
        httpClient.getParams().setAuthenticationPreemptive(true);
        HttpState cachedHttpState = (HttpState) messageContext.getProperty(HTTPConstants.CACHED_HTTP_STATE);
        if (cachedHttpState != null) {
            httpClient.setState(cachedHttpState);
        }
        httpClient.getState().setProxyCredentials(AuthScope.ANY, proxyCredentials);
    }
    config.setProxy(proxyHost, proxyPort);
}

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

public void configureHttpClient(HttpClient client) {
    Credentials credentials = new UsernamePasswordCredentials(username, password);
    if (proxy) {/*from  w w w.ja  va 2  s  . co  m*/
        client.getState().setProxyCredentials(AuthScope.ANY, credentials);
    } else {
        client.getState().setCredentials(AuthScope.ANY, credentials);
    }
}

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

public void configureHttpClient(HttpClient client) {
    Credentials credentials = new NTCredentials(username, password, host, domain);
    if (proxy) {//from  w  ww .ja  v  a  2  s  .c  o  m
        client.getState().setProxyCredentials(AuthScope.ANY, credentials);
    } else {
        client.getState().setCredentials(AuthScope.ANY, credentials);
    }
}

From source file:org.apache.clerezza.integrationtest.web.performance.Get404.java

@Override
public void run() {

    try {//  w  w w.  ja  v a2s . com
        URL serverURL = new URL(testSubjectUriPrefix + "/foobar");
        HttpClient client = new HttpClient();

        client.getState().setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password));
        HttpMethod method = new GetMethod(serverURL.toString());
        method.setRequestHeader("Accept", "*/*");
        method.setDoAuthentication(true);

        try {
            int responseCode = client.executeMethod(method);

            if (responseCode != HttpStatus.SC_NOT_FOUND) {
                throw new RuntimeException("Get404: unexpected " + "response code: " + responseCode);
            }
        } finally {
            method.releaseConnection();
        }
    } catch (MalformedURLException e) {
        throw new RuntimeException(e);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

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 2  s  . com*/
            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.BasicAuthenticationDemo.java

@SuppressWarnings("deprecation")
public static void main(String[] args) throws Exception {

    HttpClient client = new HttpClient();
    ///*from w w  w. ja  v  a  2 s.  c  om*/
    //client.getHostConfiguration().setProxy("90.0.12.21",808);

    client.getState().setCredentials("www.verisign.com", "realm",
            new UsernamePasswordCredentials("username", "password"));

    GetMethod get = new GetMethod("https://www.verisign.com/products/index.html");
    get.setDoAuthentication(true);

    int status = client.executeMethod(get);
    System.out.println(status + "" + get.getResponseBodyAsString());
    get.releaseConnection();
}

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

public static void main(String[] args) throws Exception {
    HttpClient client = new HttpClient();
    ///*from   ww  w .jav  a 2  s  . c o m*/
    client.getHostConfiguration().setProxy("90.0.12.21", 808);

    // pass our credentials to HttpClient, they will only be used for
    // authenticating to servers with realm "realm" on the host
    // "www.verisign.com", to authenticate against
    // an arbitrary realm or host change the appropriate argument to null.
    client.getState().setCredentials(new AuthScope("www.verisign.com", 443, "realm"),
            new UsernamePasswordCredentials("username", "password"));
    // create a GET method that reads a file over HTTPS, we're assuming
    // that this file requires basic authentication using the realm above.
    GetMethod get = new GetMethod("https://www.verisign.com/products/index.html");
    // Tell the GET method to automatically handle authentication. The
    // method will use any appropriate credentials to handle basic
    // authentication requests.  Setting this value to false will cause
    // any request for authentication to return with a status of 401.
    // It will then be up to the client to handle the authentication.
    get.setDoAuthentication(true);
    try {
        // execute the GET
        int status = client.executeMethod(get);
        // print the status and response
        System.out.println(status + "\n" + get.getResponseBodyAsString());
    } finally {
        // release any connection resources used by the method
        get.releaseConnection();
    }
}

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

@SuppressWarnings("deprecation")
public static void main(String[] args) throws Exception {

    //A new cookie for the domain 127.0.0.1
    //Cookie Name= ABCD   Value=00000   Path=/  MaxAge=-1   Secure=False
    Cookie mycookie = new Cookie("90.0.12.20", "ABCD", "00000", "/", -1, false);

    //Create a new HttpState container
    HttpState initialState = new HttpState();
    initialState.addCookie(mycookie);/* w ww.j  av  a  2  s. c  o m*/

    //Set to COMPATIBILITY for it to work in as many cases as possible
    initialState.setCookiePolicy(CookiePolicy.COMPATIBILITY);
    //create new client
    HttpClient httpclient = new HttpClient();
    //set the HttpState for the client
    httpclient.setState(initialState);

    GetMethod getMethod = new GetMethod(url);
    //Execute a GET method
    //int result = httpclient.executeMethod(getMethod);

    System.out.println("statusLine>>>" + getMethod.getStatusLine());

    //Get cookies stored in the HttpState for this instance of HttpClient
    Cookie[] cookies = httpclient.getState().getCookies();

    for (int i = 0; i < cookies.length; i++) {
        System.out.println("\nCookieName=" + cookies[i].getName());
        System.out.println("Value=" + cookies[i].getValue());
        System.out.println("Domain=" + cookies[i].getDomain());
    }

    getMethod.releaseConnection();
}

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

public static void main(String[] args) throws Exception {
    HttpClient client = new HttpClient();
    client.getHostConfiguration().setHost(LOGON_SITE, LOGON_PORT);

    //login.jsp->main.jsp

    PostMethod post = new PostMethod("/NationWideAdmin/test/FormLoginDemo.jsp");

    NameValuePair name = new NameValuePair("name", "wsq");
    NameValuePair pass = new NameValuePair("password", "1");
    post.setRequestBody(new NameValuePair[] { name, pass });

    //int status = client.executeMethod(post);
    System.out.println(post.getResponseBodyAsString());

    post.releaseConnection();//from  w w  w. j  a  va 2s.  c  om

    //cookie

    CookieSpec cookiespec = CookiePolicy.getDefaultSpec();
    Cookie[] cookies = cookiespec.match(LOGON_SITE, LOGON_PORT, "/NationWideAdmin/test/", false,
            client.getState().getCookies());

    if (cookies.length == 0) {
        System.out.println("None");
    } else {
        for (int i = 0; i < cookies.length; i++) {
            System.out.println(cookies[i].toString());
        }
    }

    //main2.jsp

    GetMethod get = new GetMethod("/NationWideAdmin/test/FormLoginDemo1.jsp");
    client.executeMethod(get);
    //System.out.println(get.getResponseBodyAsString());
    //
    String response = new String(get.getResponseBodyAsString().getBytes("8859_1"));
    //
    System.out.println("===================================");
    System.out.println(":");
    System.out.println(response);
    System.out.println("===================================");

    get.releaseConnection();
}