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

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

Introduction

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

Prototype

public int executeMethod(HttpMethod paramHttpMethod) throws IOException, HttpException 

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);
    String response = method.getResponseBodyAsString();

    System.out.println(response);
    method.releaseConnection();//from  w ww  .j ava 2 s . com
}

From source file:com.discursive.jccook.httpclient.MultipartPostFileExample.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();

    // Create POST method
    String weblintURL = "http://ats.nist.gov/cgi-bin/cgi.tcl/echo.cgi";
    MultipartPostMethod method = new MultipartPostMethod(weblintURL);

    File file = new File("data", "test.txt");
    File file2 = new File("data", "sample.txt");
    method.addParameter("test.txt", file);
    method.addPart(new FilePart("sample.txt", file2, "text/plain", "ISO-8859-1"));

    // Execute and print response
    client.executeMethod(method);
    String response = method.getResponseBodyAsString();
    System.out.println(response);

    method.releaseConnection();/*from  w w  w  .j a v a  2  s.com*/
}

From source file:edu.umd.cs.submit.CommandLineSubmit.java

public static void main(String[] args) {
    try {//from w  ww . j  a  v  a  2  s  .  c om
        Protocol easyhttps = new Protocol("https", new EasySSLProtocolSocketFactory(), 443);
        File home = args.length > 0 ? new File(args[0]) : new File(".");

        Protocol.registerProtocol("easyhttps", easyhttps);
        File submitFile = new File(home, ".submit");
        File submitUserFile = new File(home, ".submitUser");
        File submitIgnoreFile = new File(home, ".submitIgnore");
        File cvsIgnoreFile = new File(home, ".cvsignore");

        if (!submitFile.canRead()) {
            System.out.println("Must perform submit from a directory containing a \".submit\" file");
            System.out.println("No such file found at " + submitFile.getCanonicalPath());
            System.exit(1);
        }

        Properties p = new Properties();
        p.load(new FileInputStream(submitFile));
        String submitURL = p.getProperty("submitURL");
        if (submitURL == null) {
            System.out.println(".submit file does not contain a submitURL");
            System.exit(1);
        }
        String courseName = p.getProperty("courseName");
        String courseKey = p.getProperty("courseKey");
        String semester = p.getProperty("semester");
        String projectNumber = p.getProperty("projectNumber");
        String authenticationType = p.getProperty("authentication.type");
        String baseURL = p.getProperty("baseURL");

        System.out.println("Submitting contents of " + home.getCanonicalPath());
        System.out.println(" as project " + projectNumber + " for course " + courseName);
        FilesToIgnore ignorePatterns = new FilesToIgnore();
        addIgnoredPatternsFromFile(cvsIgnoreFile, ignorePatterns);
        addIgnoredPatternsFromFile(submitIgnoreFile, ignorePatterns);

        FindAllFiles find = new FindAllFiles(home, ignorePatterns.getPattern());
        Collection<File> files = find.getAllFiles();

        boolean createdSubmitUser = false;
        Properties userProps = new Properties();
        if (submitUserFile.canRead()) {
            userProps.load(new FileInputStream(submitUserFile));
        }
        if (userProps.getProperty("cvsAccount") == null && userProps.getProperty("classAccount") == null
                || userProps.getProperty("oneTimePassword") == null) {
            System.out.println();
            System.out.println(
                    "We need to authenticate you and create a .submitUser file so you can submit your project");

            createSubmitUser(submitUserFile, courseKey, projectNumber, authenticationType, baseURL);
            createdSubmitUser = true;
            userProps.load(new FileInputStream(submitUserFile));
        }

        MultipartPostMethod filePost = createFilePost(p, find, files, userProps);
        HttpClient client = new HttpClient();
        client.setConnectionTimeout(HTTP_TIMEOUT);
        int status = client.executeMethod(filePost);
        System.out.println(filePost.getResponseBodyAsString());
        if (status == 500 && !createdSubmitUser) {
            System.out.println("Let's try reauthenticating you");
            System.out.println();

            createSubmitUser(submitUserFile, courseKey, projectNumber, authenticationType, baseURL);
            userProps.load(new FileInputStream(submitUserFile));
            filePost = createFilePost(p, find, files, userProps);
            client = new HttpClient();
            client.setConnectionTimeout(HTTP_TIMEOUT);
            status = client.executeMethod(filePost);
            System.out.println(filePost.getResponseBodyAsString());
        }
        if (status != HttpStatus.SC_OK) {
            System.out.println("Status code: " + status);
            System.exit(1);
        }
        System.out.println("Submission accepted");
    } catch (Exception e) {
        System.out.println();
        System.out.println("An Error has occured during submission!");
        System.out.println();
        System.out.println("[DETAILS]");
        System.out.println(e.getMessage());
        e.printStackTrace(System.out);
        System.out.println();
    }
}

From source file:HttpClientPreferences.java

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

    System.err.println(/*from  w  w w. j  av  a 2s .  co m*/
            "The User Agent before changing it is: " + client.getParams().getParameter("http.useragent"));

    client.getParams().setParameter("http.useragent", "Browser at Client level");

    System.err.println("Client's User Agent is: " + client.getParams().getParameter("http.useragent"));

    GetMethod method = new GetMethod("http://www.google.com");
    method.getParams().setParameter("http.useragent", "Browser at Method level");
    try {
        client.executeMethod(method);
    } catch (Exception e) {
        System.err.println(e);
    } finally {
        method.releaseConnection();
    }
    System.err.println("Method's User Agent is: " + method.getParams().getParameter("http.useragent"));

}

From source file:com.discursive.jccook.httpclient.PostExample.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();

    // Create POST method
    String weblintURL = "http://www.discursive.com/cgi-bin/jccook/param_list.cgi";
    PostMethod method = new PostMethod(weblintURL);

    // Set parameters on POST   
    method.setParameter("test1", "Hello World");
    method.addParameter("test2", "This is a Form Submission");
    method.addParameter("Blah", "Whoop");
    method.addParameter(new NameValuePair("Blah", "Whoop2"));

    // Execute and print response
    client.executeMethod(method);
    String response = method.getResponseBodyAsString();
    System.out.println(response);

    method.releaseConnection();//  ww  w.j a v a 2 s .com
}

From source file:com.ebay.recommendations.RecommendationItemIds.java

/**
 * @param args//w w w . j a  v  a  2  s.c o m
 */
public static void main(String[] args) {
    // TODO Auto-generated method stub

    HttpClient client = new HttpClient();
    String fullUri = "https://svcs.ebay.com/services/selling/listingrecommendation/v1/item/recommendationItemIds?recommendationType=Picture&pageNumber=1&entriesPerPage=5";
    HttpMethod method = new GetMethod(fullUri);
    // REPLACE YOUR TOKEN IN THE <YOUR_TOKEN_HERE> PLACE HOLDER
    method.addRequestHeader("Authorization", "TOKEN <YOUR_TOKEN_HERE>");
    method.addRequestHeader("X-EBAY-GLOBAL-ID", "EBAY-US");

    method.addRequestHeader("Accept", "application/xml");

    try {
        client.executeMethod(method);
        String response = method.getResponseBodyAsString();
        System.out.println(response);
    } catch (Exception e) {
        e.printStackTrace();
    }

}

From source file:TestCookieDecode.java

/**
 * @param args//www.j  a  va 2  s.c  o  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: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: 
    /*//w  w  w.j a va 2s .c  om
    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);
    System.out.println("Login form get: " + authget.getStatusLine().toString());
    // release any connection resources used by the method
    authget.releaseConnection();//from   w w  w.  j  a  v  a2 s  .  c om
    // 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//  ww w.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);
        }
    }
}