Example usage for org.apache.commons.httpclient.methods GetMethod GetMethod

List of usage examples for org.apache.commons.httpclient.methods GetMethod GetMethod

Introduction

In this page you can find the example usage for org.apache.commons.httpclient.methods GetMethod GetMethod.

Prototype

public GetMethod(String uri) 

Source Link

Usage

From source file:com.discursive.jccook.httpclient.BasicAuthExample.java

public static void main(String[] args) throws HttpException, IOException {
    // Configure Logging
    System.setProperty("org.apache.commons.logging.Log", "org.apache.commons.logging.impl.SimpleLog");
    System.setProperty("org.apache.commons.logging.simplelog.showdatetime", "true");
    System.setProperty("org.apache.commons.logging.simplelog.log.httpclient.wire", "debug");
    System.setProperty("org.apache.commons.logging.simplelog.log.org.apache.commons.httpclient", "debug");

    HttpClient client = new HttpClient();
    HttpState state = client.getState();
    HttpClientParams params = client.getParams();

    // Set credentials on the client
    Credentials credentials = new UsernamePasswordCredentials("testuser", "crazypass");
    state.setCredentials(null, null, credentials);
    params.setAuthenticationPreemptive(true);

    String url = "http://www.discursive.com/jccook/auth/";
    HttpMethod method = new GetMethod(url);

    client.executeMethod(method);/*  ww  w.ja va2 s.  c  o  m*/
    String response = method.getResponseBodyAsString();

    System.out.println(response);
    method.releaseConnection();
}

From source file:httpsdemo.client.Client.java

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

    File clientKeystore = new File("certs/clientKeystore.jks");
    File truststore = new File("certs/commonTruststore.jks");

    // Send HTTP GET request to query customer info - using portable HttpClient method
    Protocol authhttps = new Protocol("https", new AuthSSLProtocolSocketFactory(clientKeystore.toURI().toURL(),
            "password", truststore.toURI().toURL(), "password"), 9000);
    Protocol.registerProtocol("https", authhttps);

    System.out.println("Sending HTTPS GET request to query customer info");
    HttpClient httpclient = new HttpClient();
    GetMethod httpget = new GetMethod(BASE_SERVICE_URL + "/123");
    httpget.addRequestHeader("Accept", "text/xml");

    // If Basic Authentication required could use: 
    /*//from  ww  w  . j  a va 2s  . c o  m
    String authorizationHeader = "Basic " 
       + org.apache.cxf.common.util.Base64Utility.encode("username:password".getBytes());
    httpget.addRequestHeader("Authorization", authorizationHeader);
    */
    try {
        httpclient.executeMethod(httpget);
        System.out.println(httpget.getResponseBodyAsString());
    } finally {
        httpget.releaseConnection();
    }

    /*
     *  Send HTTP PUT request to update customer info, using CXF WebClient method
     *  Note: if need to use basic authentication, use the WebClient.create(baseAddress,
     *  username,password,configFile) variant, where configFile can be null if you're
     *  not using certificates.
     */
    System.out.println("Sending HTTPS PUT to update customer name");
    WebClient wc = WebClient.create(BASE_SERVICE_URL, CLIENT_CONFIG_FILE);
    Customer customer = new Customer();
    customer.setId(123);
    customer.setName("Mary");
    Response resp = wc.put(customer);

    /*
     *  Send HTTP POST request to add customer, using JAXRSClientProxy
     *  Note: if need to use basic authentication, use the JAXRSClientFactory.create(baseAddress,
     *  username,password,configFile) variant, where configFile can be null if you're
     *  not using certificates.
     */
    System.out.println("\n");
    System.out.println("Sending HTTPS POST request to add customer");
    CustomerService proxy = JAXRSClientFactory.create(BASE_SERVICE_URL, CustomerService.class,
            CLIENT_CONFIG_FILE);
    customer = new Customer();
    customer.setName("Jack");
    resp = wc.post(customer);

    System.out.println("\n");
    System.exit(0);
}

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);/* w w w . jav a2 s .co  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:fr.cls.atoll.motu.library.misc.cas.HttpClientTutorial.java

public static void main(String[] args) {

    // test();//from w  ww.  j  av a  2s .c om
    // System.setProperty("proxyHost", "proxy.cls.fr"); // adresse IP
    // System.setProperty("proxyPort", "8080");
    // System.setProperty("socksProxyPort", "1080");
    //
    // Authenticator.setDefault(new MyAuthenticator());

    // Create an instance of HttpClient.
    // HttpClient client = new HttpClient();
    HttpClient client = new HttpClient(new MultiThreadedHttpConnectionManager());
    // Create a method instance.
    GetMethod method = new GetMethod(url);

    HostConfiguration hostConfiguration = new HostConfiguration();
    hostConfiguration.setProxy("proxy.cls.fr", 8080);
    client.setHostConfiguration(hostConfiguration);

    // Provide custom retry handler is necessary
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(3, false));
    // String username = "xxx";
    // String password = "xxx";
    // Credentials credentials = new UsernamePasswordCredentials(username, password);
    // AuthScope authScope = new AuthScope("proxy.cls.fr", 8080);
    //     
    // client.getState().setProxyCredentials(authScope, credentials);

    try {
        // Execute the method.
        int statusCode = client.executeMethod(method);

        if (statusCode != HttpStatus.SC_OK) {
            System.err.println("Method failed: " + method.getStatusLine());
        }

        // Read the response body.
        byte[] responseBody = method.getResponseBody();

        // Deal with the response.
        // Use caution: ensure correct character encoding and is not binary data
        System.out.println(new String(responseBody));

    } catch (HttpException e) {
        System.err.println("Fatal protocol violation: " + e.getMessage());
        e.printStackTrace();
    } catch (IOException e) {
        System.err.println("Fatal transport error: " + e.getMessage());
        e.printStackTrace();
    } finally {
        // Release the connection.
        method.releaseConnection();
    }
}

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/*  www .  j  a  v  a 2s  .c  o  m*/
    // 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:BasicAuthenticationExample.java

public static void main(String[] args) throws Exception {
    HttpClient client = new HttpClient();

    // 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);// ww  w.j av  a  2  s.c  om

    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: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   www.j  a va 2 s.  c  om
        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:AlternateAuthenticationExample.java

public static void main(String[] args) throws Exception {
    HttpClient client = new HttpClient();
    client.getState().setCredentials(new AuthScope("myhost", 80, "myrealm"),
            new UsernamePasswordCredentials("username", "password"));
    // Suppose the site supports several authetication schemes: NTLM and Basic
    // Basic authetication is considered inherently insecure. Hence, NTLM authentication
    // is used per default

    // This is to make HttpClient pick the Basic authentication scheme over NTLM & Digest
    List authPrefs = new ArrayList(3);
    authPrefs.add(AuthPolicy.BASIC);/*from  w w w .j a  va2s  .c  om*/
    authPrefs.add(AuthPolicy.NTLM);
    authPrefs.add(AuthPolicy.DIGEST);
    client.getParams().setParameter(AuthPolicy.AUTH_SCHEME_PRIORITY, authPrefs);

    GetMethod httpget = new GetMethod("http://myhost/protected/auth-required.html");

    try {
        int status = client.executeMethod(httpget);
        // print the status and response
        System.out.println(httpget.getStatusLine());
        System.out.println(httpget.getResponseBodyAsString());
    } finally {
        // release any connection resources used by the method
        httpget.releaseConnection();
    }
}

From source file:TrivialApp.java

public static void main(String[] args) {
    if ((args.length != 1) && (args.length != 3)) {
        printUsage();// www .j av a2 s  . c om
        System.exit(-1);
    }

    Credentials creds = null;
    if (args.length >= 3) {
        creds = new UsernamePasswordCredentials(args[1], args[2]);
    }

    //create a singular HttpClient object
    HttpClient client = new HttpClient();

    //establish a connection within 5 seconds
    client.getHttpConnectionManager().getParams().setConnectionTimeout(5000);

    //set the default credentials
    if (creds != null) {
        client.getState().setCredentials(AuthScope.ANY, creds);
    }

    String url = args[0];
    HttpMethod method = null;

    //create a method object
    method = new GetMethod(url);
    method.setFollowRedirects(true);
    //} catch (MalformedURLException murle) {
    //    System.out.println("<url> argument '" + url
    //            + "' is not a valid URL");
    //    System.exit(-2);
    //}

    //execute the method
    String responseBody = null;
    try {
        client.executeMethod(method);
        responseBody = method.getResponseBodyAsString();
    } catch (HttpException he) {
        System.err.println("Http error connecting to '" + url + "'");
        System.err.println(he.getMessage());
        System.exit(-4);
    } catch (IOException ioe) {
        System.err.println("Unable to connect to '" + url + "'");
        System.exit(-3);
    }

    //write out the request headers
    System.out.println("*** Request ***");
    System.out.println("Request Path: " + method.getPath());
    System.out.println("Request Query: " + method.getQueryString());
    Header[] requestHeaders = method.getRequestHeaders();
    for (int i = 0; i < requestHeaders.length; i++) {
        System.out.print(requestHeaders[i]);
    }

    //write out the response headers
    System.out.println("*** Response ***");
    System.out.println("Status Line: " + method.getStatusLine());
    Header[] responseHeaders = method.getResponseHeaders();
    for (int i = 0; i < responseHeaders.length; i++) {
        System.out.print(responseHeaders[i]);
    }

    //write out the response body
    System.out.println("*** Response Body ***");
    System.out.println(responseBody);

    //clean up the connection resources
    method.releaseConnection();

    System.exit(0);
}

From source file:de.mpg.escidoc.services.cone.util.CCCrawler.java

public static void main(String[] args) throws Exception {
    HttpClient httpClient = new HttpClient();

    querier = QuerierFactory.newQuerier(false);

    // field_commercial
    for (YesNo fieldCommercial : YesNo.values()) {
        // field_derivatives
        for (YesNo fieldDerivatives : YesNo.values()) {
            // field_derivatives
            for (Jurisdiction fieldJurisdiction : Jurisdiction.values()) {
                String licenceUrl = ccUrl + "&field_commercial=" + fieldCommercial.toString()
                        + "&field_derivatives=" + fieldDerivatives.toString() + "&field_jurisdiction="
                        + fieldJurisdiction.toString() + "&lang=de_DE";
                System.out.println(licenceUrl);
                GetMethod method = new GetMethod(licenceUrl);
                ProxyHelper.executeMethod(httpClient, method);

                if (method.getStatusCode() == 200) {
                    TreeFragment fragment = new TreeFragment();

                    String key1 = "urn:cone:commercial";
                    String key3 = "urn:cone:jurisdiction";

                    List<LocalizedTripleObject> list = new ArrayList<LocalizedTripleObject>();
                    list.add(new LocalizedString(fieldCommercial.toBoolean()));
                    fragment.put(key1, list);

                    List<LocalizedTripleObject> list2 = new ArrayList<LocalizedTripleObject>();
                    list2.add(new LocalizedString(fieldDerivatives.toBoolean()));
                    fragment.put("urn:cone:derivatives", list2);

                    List<LocalizedTripleObject> list3 = new ArrayList<LocalizedTripleObject>();
                    list3.add(new LocalizedString(fieldJurisdiction.toString()));
                    fragment.put(key3, list3);

                    String codeToCopy = extractCode(method);

                    Pattern urlPattern = Pattern.compile("href=\"([^\"]+)\"");
                    Matcher urlMatcher = urlPattern.matcher(codeToCopy);
                    if (urlMatcher.find()) {
                        String url = urlMatcher.group(1);
                        fragment.setSubject(url);

                        Pattern versionPattern = Pattern.compile("/(\\d+\\.\\d+)/[^/]+/$");
                        Matcher versionMatcher = versionPattern.matcher(url);
                        if (versionMatcher.find()) {
                            list = new ArrayList<LocalizedTripleObject>();
                            list.add(new LocalizedString(versionMatcher.group(1)));
                            fragment.put("urn:cone:version", list);
                        }//from  w ww  .j  ava  2 s .c  o  m

                        Pattern imgPattern = Pattern.compile("src=\"([^\"]+)\"");
                        Matcher imgMatcher = imgPattern.matcher(codeToCopy);
                        if (imgMatcher.find()) {
                            list = new ArrayList<LocalizedTripleObject>();
                            list.add(new LocalizedString(imgMatcher.group(1)));
                            fragment.put("http://xmlns.com/foaf/0.1/depiction", list);
                        }

                        GetMethod method2 = new GetMethod(url);
                        ProxyHelper.executeMethod(httpClient, method2);
                        String page = method2.getResponseBodyAsString();

                        Pattern namePattern = Pattern.compile("<h2 property=\"dc:title\">([^<]+)</h2>");
                        Matcher nameMatcher = namePattern.matcher(page);
                        if (nameMatcher.find()) {
                            list = new ArrayList<LocalizedTripleObject>();
                            list.add(new LocalizedString(nameMatcher.group(1)));
                            fragment.put("http://purl.org/dc/elements/1.1/title", list);
                        }

                        List<LocalizedTripleObject> languages = extractLanguages(page, url);

                        fragment.put("urn:cone:translation", languages);

                        querier.delete("cclicences", url);
                        querier.create("cclicences", url, fragment);
                    }

                } else {
                    System.out.println("Not found: " + licenceUrl);
                }
            }
        }
    }
    querier.release();
}