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

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

Introduction

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

Prototype

public HostConfiguration getHostConfiguration()

Source Link

Usage

From source file:TestCookieDecode.java

/**
 * @param args//from  w w  w.  j a  va2 s. co  m
 */
public static void main(String[] args) throws Exception {
    // // TODO Auto-generated method stub
    // DefaultCryptoBeanDefinition() blowfishCrypto = new
    // DefaultCryptoBeanDefinition();
    // blowfishCrypto.setAlgorithm("Blowfish");
    // blowfishCrypto.setTransformation("Blowfish/CBC/NoPadding");
    // blowfishCrypto.setKey(cryptoKey);
    // blowfishCrypto.setProvider("CryptixCrypto");
    //
    // java.security.Security.addProvider(new
    // cryptix.jce.provider.CryptixCrypto());
    // String key="^#16qweqv88cde729!@#$3450abfg^%";
    // SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(),
    // "Blowfish");
    // Cipher deCipher =
    // Cipher.getInstance("Blowfish/CBC/NoPadding","CryptixCrypto");
    // deCipher.init(Cipher.DECRYPT_MODE, secretKey);
    // byte[] ret= deCipher.doFinal(
    // Base64Util.decode("ihxD3imKsk724mCURZhHkD3QbIzWcXp3NbZBi72ilN9td+XSaN5nYUH1N7JwXKMj"));
    // System.out.println(new String(ret).substring(8).trim());

    HttpClient client = new HttpClient();
    client.getHostConfiguration().setHost("www.guahao.com", 80);
    PostMethod post = new PostMethod("/outSysGetUserCookieValue");
    NameValuePair name = new NameValuePair("signdata", "PjPQvzc6j1UOmThSb3IUkw==");
    NameValuePair pass = new NameValuePair("cookieValue",
            "{\"__uli__\":\"sDZXBw9ZZm/QM3lksxZ7mVjUFIbpup7//oPTueSeWY1XhNAQhIPSPiPFV5EqKMoO3qeJSLoBdt3LxwvuTUSW9g==\"}");
    post.setRequestBody(new NameValuePair[] { name, pass });
    client.executeMethod(post);
    System.out.println(post.getResponseBodyAsString());
    post.releaseConnection();

    String signdata = DESUtils.dCode("Py8o3huCfMcSJR4HBjDe0w==", EncodeKeyConstants.OUT_SYS_USER_KEY);
    System.out.println(signdata);

}

From source file:BasicAuthenticationExecuteJSPMethod.java

public static void main(String args[]) throws Exception {

    HttpClient client = new HttpClient();
    client.getParams().setParameter("parameterKey", "value");

    HostConfiguration host = client.getHostConfiguration();
    host.setHost(new URI("http://localhost:8080", true));

    GetMethod method = new GetMethod("/commons/folder/protected.jsp");
    try {/*from   w w  w .  ja v  a 2s. c  om*/
        client.executeMethod(host, method);
        System.err.println(method.getStatusLine());
        System.err.println(method.getResponseBodyAsString());
    } catch (Exception e) {
        System.err.println(e);
    } finally {
        method.releaseConnection();
    }
}

From source file:HttpClientParameter.java

public static void main(String args[]) throws Exception {

    HttpClient client = new HttpClient();
    client.getParams().setParameter("http.useragent", "My Browser");

    HostConfiguration host = client.getHostConfiguration();
    host.setHost("www.google.com");

    GetMethod method = new GetMethod("http://www.yahoo.com");

    int returnCode = client.executeMethod(host, method);

    System.err.println(method.getResponseBodyAsString());

    System.err// w ww .j a va 2 s  . c  om
            .println("User-Agent: " + method.getHostConfiguration().getParams().getParameter("http.useragent"));

    System.err.println("User-Agent: " + method.getParams().getParameter("http.useragent"));

    method.releaseConnection();
}

From source file:BasicAuthenticationForJSPPage.java

public static void main(String args[]) throws Exception {

    HttpClient client = new HttpClient();
    client.getParams().setParameter("http.useragent", "My Browser");

    HostConfiguration host = client.getHostConfiguration();
    host.setHost(new URI("http://localhost:8080", true));

    Credentials credentials = new UsernamePasswordCredentials("tomcat", "tomcat");
    AuthScope authScope = new AuthScope(host.getHost(), host.getPort());
    HttpState state = client.getState();
    state.setCredentials(authScope, credentials);

    GetMethod method = new GetMethod("/commons/chapter01/protected.jsp");
    try {//from ww  w . j  av  a  2  s  .c o  m
        client.executeMethod(host, method);
        System.err.println(method.getStatusLine());
        System.err.println(method.getResponseBodyAsString());
    } catch (Exception e) {
        System.err.println(e);
    } finally {
        method.releaseConnection();
    }
}

From source file:FormLoginDemo.java

public static void main(String[] args) throws Exception {

    HttpClient client = new HttpClient();
    client.getHostConfiguration().setHost(LOGON_SITE, LOGON_PORT, "http");
    client.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
    // 'developer.java.sun.com' has cookie compliance problems
    // Their session cookie's domain attribute is in violation of the RFC2109
    // We have to resort to using compatibility cookie policy

    GetMethod authget = new GetMethod("/servlet/SessionServlet");

    client.executeMethod(authget);/*from w  w  w  .  j a v  a 2 s . c o m*/
    System.out.println("Login form get: " + authget.getStatusLine().toString());
    // release any connection resources used by the method
    authget.releaseConnection();
    // See if we got any cookies
    CookieSpec cookiespec = CookiePolicy.getDefaultSpec();
    Cookie[] initcookies = cookiespec.match(LOGON_SITE, LOGON_PORT, "/", false, client.getState().getCookies());
    System.out.println("Initial set of cookies:");
    if (initcookies.length == 0) {
        System.out.println("None");
    } else {
        for (int i = 0; i < initcookies.length; i++) {
            System.out.println("- " + initcookies[i].toString());
        }
    }

    PostMethod authpost = new PostMethod("/servlet/SessionServlet");
    // Prepare login parameters
    NameValuePair action = new NameValuePair("action", "login");
    NameValuePair url = new NameValuePair("url", "/index.html");
    NameValuePair userid = new NameValuePair("UserId", "userid");
    NameValuePair password = new NameValuePair("Password", "password");
    authpost.setRequestBody(new NameValuePair[] { action, url, userid, password });

    client.executeMethod(authpost);
    System.out.println("Login form post: " + authpost.getStatusLine().toString());
    // release any connection resources used by the method
    authpost.releaseConnection();
    // See if we got any cookies
    // The only way of telling whether logon succeeded is 
    // by finding a session cookie
    Cookie[] logoncookies = cookiespec.match(LOGON_SITE, LOGON_PORT, "/", false,
            client.getState().getCookies());
    System.out.println("Logon cookies:");
    if (logoncookies.length == 0) {
        System.out.println("None");
    } else {
        for (int i = 0; i < logoncookies.length; i++) {
            System.out.println("- " + logoncookies[i].toString());
        }
    }
    // Usually a successful form-based login results in a redicrect to 
    // another url
    int statuscode = authpost.getStatusCode();
    if ((statuscode == HttpStatus.SC_MOVED_TEMPORARILY) || (statuscode == HttpStatus.SC_MOVED_PERMANENTLY)
            || (statuscode == HttpStatus.SC_SEE_OTHER) || (statuscode == HttpStatus.SC_TEMPORARY_REDIRECT)) {
        Header header = authpost.getResponseHeader("location");
        if (header != null) {
            String newuri = header.getValue();
            if ((newuri == null) || (newuri.equals(""))) {
                newuri = "/";
            }
            System.out.println("Redirect target: " + newuri);
            GetMethod redirect = new GetMethod(newuri);

            client.executeMethod(redirect);
            System.out.println("Redirect: " + redirect.getStatusLine().toString());
            // release any connection resources used by the method
            redirect.releaseConnection();
        } else {
            System.out.println("Invalid redirect");
            System.exit(1);
        }
    }
}

From source file:com.mytutorials.httpclient.FormLoginDemo.java

public static void main(String[] args) throws Exception {

    HttpClient client = new HttpClient();
    client.getHostConfiguration().setHost(LOGON_SITE, LOGON_PORT, "http");
    client.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
    // 'developer.java.sun.com' has cookie compliance problems
    // Their session cookie's domain attribute is in violation of the
    // RFC2109/*w w w .  j  a  va 2  s  .com*/
    // We have to resort to using compatibility cookie policy

    GetMethod authget = new GetMethod("/servlet/SessionServlet");

    client.executeMethod(authget);
    System.out.println("Login form get: " + authget.getStatusLine().toString());
    // release any connection resources used by the method
    authget.releaseConnection();
    // See if we got any cookies
    CookieSpec cookiespec = CookiePolicy.getDefaultSpec();
    Cookie[] initcookies = cookiespec.match(LOGON_SITE, LOGON_PORT, "/", false, client.getState().getCookies());
    System.out.println("Initial set of cookies:");
    if (initcookies.length == 0) {
        System.out.println("None");
    } else {
        for (int i = 0; i < initcookies.length; i++) {
            System.out.println("- " + initcookies[i].toString());
        }
    }

    PostMethod authpost = new PostMethod("/servlet/SessionServlet");
    // Prepare login parameters
    NameValuePair action = new NameValuePair("action", "login");
    NameValuePair url = new NameValuePair("url", "/index.html");
    NameValuePair userid = new NameValuePair("UserId", "userid");
    NameValuePair password = new NameValuePair("Password", "password");
    authpost.setRequestBody(new NameValuePair[] { action, url, userid, password });

    client.executeMethod(authpost);
    System.out.println("Login form post: " + authpost.getStatusLine().toString());
    // release any connection resources used by the method
    authpost.releaseConnection();
    // See if we got any cookies
    // The only way of telling whether logon succeeded is
    // by finding a session cookie
    Cookie[] logoncookies = cookiespec.match(LOGON_SITE, LOGON_PORT, "/", false,
            client.getState().getCookies());
    System.out.println("Logon cookies:");
    if (logoncookies.length == 0) {
        System.out.println("None");
    } else {
        for (int i = 0; i < logoncookies.length; i++) {
            System.out.println("- " + logoncookies[i].toString());
        }
    }
    // Usually a successful form-based login results in a redicrect to
    // another url
    int statuscode = authpost.getStatusCode();
    if ((statuscode == HttpStatus.SC_MOVED_TEMPORARILY) || (statuscode == HttpStatus.SC_MOVED_PERMANENTLY)
            || (statuscode == HttpStatus.SC_SEE_OTHER) || (statuscode == HttpStatus.SC_TEMPORARY_REDIRECT)) {
        Header header = authpost.getResponseHeader("location");
        if (header != null) {
            String newuri = header.getValue();
            if ((newuri == null) || (newuri.equals(""))) {
                newuri = "/";
            }
            System.out.println("Redirect target: " + newuri);
            GetMethod redirect = new GetMethod(newuri);

            client.executeMethod(redirect);
            System.out.println("Redirect: " + redirect.getStatusLine().toString());
            // release any connection resources used by the method
            redirect.releaseConnection();
        } else {
            System.out.println("Invalid redirect");
            System.exit(1);
        }
    }
}

From source file:com.djimenez.tuenti.example.FormLoginDemo.java

public static void main(final String[] args) throws Exception {

    final HttpClient client = new HttpClient();

    client.getHostConfiguration().setHost(LOGON_SITE, LOGON_PORT, "http");
    client.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
    // 'developer.java.sun.com' has cookie compliance problems
    // Their session cookie's domain attribute is in violation of the RFC2109
    // We have to resort to using compatibility cookie policy

    final GetMethod authget = new GetMethod(LOGON_PATH);
    authget.setFollowRedirects(true);//from  w  ww. ja v a2  s .  c  o m

    client.executeMethod(authget);
    System.out.println("Login form get: " + authget.getStatusLine().toString());
    // release any connection resources used by the method
    authget.releaseConnection();
    // See if we got any cookies
    final CookieSpec cookiespec = CookiePolicy.getDefaultSpec();
    final Cookie[] initcookies = cookiespec.match(LOGON_SITE, LOGON_PORT, "/", false,
            client.getState().getCookies());
    System.out.println("Initial set of cookies:");

    checkCookies(initcookies);

    final PostMethod authpost = new PostMethod(LOGON_PATH);

    // Prepare login parameters
    final NameValuePair action = new NameValuePair("action", "do_login");
    final NameValuePair url = new NameValuePair("url", "/?m=Login&func=do_login");
    final NameValuePair userid = new NameValuePair("email", "david.jimenez19%40gmail.com");
    final NameValuePair password = new NameValuePair("input_password", "linda1");
    final NameValuePair timeZone = new NameValuePair("timezone", "1");
    final NameValuePair timeStamp = new NameValuePair("timezone", "13034395121");

    authpost.setRequestBody(new NameValuePair[] { action, url, userid, password, timeZone, timeStamp });

    client.executeMethod(authpost);

    System.out.println("Login form post: " + authpost.getStatusLine().toString());
    // release any connection resources used by the method
    authpost.releaseConnection();
    // See if we got any cookies
    // The only way of telling whether logon succeeded is
    // by finding a session cookie
    final Cookie[] logoncookies = cookiespec.match(LOGON_SITE, LOGON_PORT, "/", false,
            client.getState().getCookies());
    System.out.println("Logon cookies:" + logoncookies);

    checkCookies(logoncookies);

    manageRequest(client, authpost);
}

From source file:Correct.java

public static void main(String[] args) {

    String URLL = "";
    HttpClient client = new HttpClient();
    HttpMethod method = new PostMethod(URLL);
    method.setDoAuthentication(true);//w  ww  .jav a 2s .com
    HostConfiguration hostConfig = client.getHostConfiguration();
    hostConfig.setHost("172.29.38.8");
    hostConfig.setProxy("172.29.90.4", 8);
    //   NTCredentials proxyCredentials = new NTCredentials("", "", "", "");
    client.getState().setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("", ""));
    ////        try {
    ////            URL url = new URL("");
    ////            HttpURLConnection urls = (HttpURLConnection) url.openConnection();
    ////            
    ////           
    ////        } catch (MalformedURLException ex) {
    ////            Logger.getLogger(Correct.class.getName()).log(Level.SEVERE, null, ex);
    ////        } catch (IOException ex) {
    ////            Logger.getLogger(Correct.class.getName()).log(Level.SEVERE, null, ex);
    ////        }
    try {
        // send the transaction
        client.executeMethod(hostConfig, method);
        StatusLine status = method.getStatusLine();

        if (status != null && method.getStatusCode() == 200) {

            System.out.println(method.getResponseBodyAsString() + "\n Status code : " + status);

        } else {

            System.err.println(method.getStatusLine() + "\n: Posting Failed !");
        }

    } catch (IOException ioe) {

        ioe.printStackTrace();

    }
    method.releaseConnection();

}

From source file:MultiThreadedExample.java

public static void main(String[] args) {

    // Create an HttpClient with the MultiThreadedHttpConnectionManager.
    // This connection manager must be used if more than one thread will
    // be using the HttpClient.
    HttpClient httpClient = new HttpClient(new MultiThreadedHttpConnectionManager());
    // Set the default host/protocol for the methods to connect to.
    // This value will only be used if the methods are not given an absolute URI
    httpClient.getHostConfiguration().setHost("jakarta.apache.org", 80, "http");

    // create an array of URIs to perform GETs on
    String[] urisToGet = { "/", "/commons/", "/commons/httpclient/",
            "http://svn.apache.org/viewvc/jakarta/httpcomponents/oac.hc3x/" };

    // create a thread for each URI
    GetThread[] threads = new GetThread[urisToGet.length];
    for (int i = 0; i < threads.length; i++) {
        GetMethod get = new GetMethod(urisToGet[i]);
        get.setFollowRedirects(true);/*from   w ww.  ja v  a  2s  .  c  o m*/
        threads[i] = new GetThread(httpClient, get, i + 1);
    }

    // start the threads
    for (int j = 0; j < threads.length; j++) {
        threads[j].start();
    }

}

From source file:be.fedict.trust.service.util.ClockDriftUtil.java

public static Date executeTSP(ClockDriftConfigEntity clockDriftConfig, NetworkConfig networkConfig)
        throws IOException, TSPException {

    LOG.debug("clock drift detection: " + clockDriftConfig.toString());

    TimeStampRequestGenerator requestGen = new TimeStampRequestGenerator();

    TimeStampRequest request = requestGen.generate(TSPAlgorithms.SHA1, new byte[20], BigInteger.valueOf(100));
    byte[] requestData = request.getEncoded();

    HttpClient httpClient = new HttpClient();

    if (null != networkConfig) {
        httpClient.getHostConfiguration().setProxy(networkConfig.getProxyHost(), networkConfig.getProxyPort());
    }/*from  w  w w . j  a v  a2 s.  c  o m*/

    PostMethod postMethod = new PostMethod(clockDriftConfig.getServer());
    postMethod.setRequestEntity(new ByteArrayRequestEntity(requestData, "application/timestamp-query"));

    int statusCode = httpClient.executeMethod(postMethod);
    if (statusCode != HttpStatus.SC_OK) {
        throw new TSPException("Error contacting TSP server " + clockDriftConfig.getServer());
    }

    TimeStampResponse tspResponse = new TimeStampResponse(postMethod.getResponseBodyAsStream());
    postMethod.releaseConnection();

    return tspResponse.getTimeStampToken().getTimeStampInfo().getGenTime();
}