Example usage for org.apache.commons.httpclient.methods PostMethod setRequestBody

List of usage examples for org.apache.commons.httpclient.methods PostMethod setRequestBody

Introduction

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

Prototype

public void setRequestBody(NameValuePair[] paramArrayOfNameValuePair) throws IllegalArgumentException 

Source Link

Usage

From source file:com.discursive.jccook.httpclient.PostFileExample.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";
    PostMethod method = new PostMethod(weblintURL);

    File file = new File("project.xml");
    method.setRequestBody(new FileInputStream(file));
    method.setRequestContentLength((long) file.length());

    // Execute and print response
    client.executeMethod(method);// www  . j  a v a 2s .com
    String response = method.getResponseBodyAsString();
    System.out.println(response);

    method.releaseConnection();
}

From source file:de.mpg.escidoc.services.edoc.CreatePurgeScript2.java

/**
 * @param args/*from  w  w  w.ja  v a 2 s.c  o m*/
 */
public static void main(String[] args) throws Exception {
    CORESERVICES_URL = PropertyReader.getProperty("escidoc.framework_access.framework.url");

    String userHandle = AdminHelper.loginUser(args[0], args[1]);

    logger.info("Querying core-services...");
    HttpClient httpClient = new HttpClient();
    String filter = "<param><filter name=\"http://escidoc.de/core/01/structural-relations/context\">"
            + IMPORT_CONTEXT
            + "</filter><filter name=\"/properties/public-status\">released</filter><order-by>http://escidoc.de/core/01/properties/creation-date</order-by><limit>0</limit></param>";

    PostMethod postMethod = new PostMethod(CORESERVICES_URL + "/ir/items/filter");
    postMethod.setRequestHeader("Cookie", "escidocCookie=" + userHandle);
    postMethod.setRequestBody(filter);

    ProxyHelper.executeMethod(httpClient, postMethod);
    String response = postMethod.getResponseBodyAsString();
    logger.info("...done!");

    FileWriter xmlData = new FileWriter("xmlData.xml");
    xmlData.write(response);
    xmlData.close();
    //System.out.println(response);

    logger.info("Transforming result...");
    XSLTTransform transform = new XSLTTransform();
    File stylesheet = new File("src/main/resources/itemlist2purgescript.xslt");
    FileOutputStream outputStream = new FileOutputStream("purge.sh");
    transform.transform(response, stylesheet, outputStream);
    logger.info("...done!");

    logger.info("Finished!");
}

From source file:de.mpg.escidoc.services.edoc.BatchUpdate.java

/**
 * @param args/* w w w  .java  2s.c o m*/
 */
public static void main(String[] args) throws Exception {
    CORESERVICES_URL = PropertyReader.getProperty("escidoc.framework_access.framework.url");

    String userHandle = AdminHelper.loginUser("import_user", "");

    logger.info("Querying core-services...");
    HttpClient httpClient = new HttpClient();
    String filter = "<param><filter name=\"http://escidoc.de/core/01/structural-relations/context\">"
            + IMPORT_CONTEXT
            + "</filter><order-by>http://escidoc.de/core/01/properties/creation-date</order-by><limit>0</limit></param>";

    logger.info("Filter: " + filter);

    PostMethod postMethod = new PostMethod(CORESERVICES_URL + "/ir/items/filter");

    postMethod.setRequestBody(filter);

    ProxyHelper.executeMethod(httpClient, postMethod);

    //        GetMethod getMethod = new GetMethod(CORESERVICES_URL + "/ir/item/escidoc:100220");
    //        getMethod.setRequestHeader("Cookie", "escidocCookie=" + userHandle)ProxyHelper.executeMethod(httpClient, getMethod)hod(httpClient, getMethod);

    String response = postMethod.getResponseBodyAsString();
    logger.info("...done!");

    System.out.println(response);

    while (response.contains("<escidocItem:item")) {

        int startPos = response.indexOf("<escidocItem:item");
        int endPos = response.indexOf("</escidocItem:item>");

        String item = response.substring(startPos, endPos + 19);

        response = response.substring(endPos + 19);

        startPos = item.indexOf("xlink:href=\"");
        endPos = item.indexOf("\"", startPos + 12);

        String objId = item.substring(startPos + 12, endPos);

        System.out.print(objId);

        if (item.contains("escidoc:22019")) {
            item = item.replaceAll("escidoc:22019", "escidoc:55222");

            PutMethod putMethod = new PutMethod(CORESERVICES_URL + objId);

            putMethod.setRequestHeader("Cookie", "escidocCookie=" + userHandle);
            putMethod.setRequestEntity(new StringRequestEntity(item));
            ProxyHelper.executeMethod(httpClient, putMethod);

            String result = putMethod.getResponseBodyAsString();

            //System.out.println(item);

            startPos = result.indexOf("last-modification-date=\"");
            endPos = result.indexOf("\"", startPos + 24);
            String modDate = result.substring(startPos + 24, endPos);
            //System.out.println("modDate: " + modDate);
            String param = "<param last-modification-date=\"" + modDate
                    + "\"><url>http://pubman.mpdl.mpg.de/pubman/item/" + objId.substring(4) + "</url></param>";
            postMethod = new PostMethod(CORESERVICES_URL + objId + "/assign-version-pid");
            postMethod.setRequestHeader("Cookie", "escidocCookie=" + userHandle);
            postMethod.setRequestEntity(new StringRequestEntity(param));
            ProxyHelper.executeMethod(httpClient, postMethod);
            result = postMethod.getResponseBodyAsString();
            //System.out.println("Result: " + result);

            startPos = result.indexOf("last-modification-date=\"");
            endPos = result.indexOf("\"", startPos + 24);
            modDate = result.substring(startPos + 24, endPos);
            //System.out.println("modDate: " + modDate);
            param = "<param last-modification-date=\"" + modDate
                    + "\"><comment>Batch repair of organizational unit identifier</comment></param>";
            postMethod = new PostMethod(CORESERVICES_URL + objId + "/submit");
            postMethod.setRequestHeader("Cookie", "escidocCookie=" + userHandle);
            postMethod.setRequestEntity(new StringRequestEntity(param));
            ProxyHelper.executeMethod(httpClient, postMethod);
            result = postMethod.getResponseBodyAsString();
            //System.out.println("Result: " + result);

            startPos = result.indexOf("last-modification-date=\"");
            endPos = result.indexOf("\"", startPos + 24);
            modDate = result.substring(startPos + 24, endPos);
            //System.out.println("modDate: " + modDate);
            param = "<param last-modification-date=\"" + modDate
                    + "\"><comment>Batch repair of organizational unit identifier</comment></param>";
            postMethod = new PostMethod(CORESERVICES_URL + objId + "/release");
            postMethod.setRequestHeader("Cookie", "escidocCookie=" + userHandle);
            postMethod.setRequestEntity(new StringRequestEntity(param));
            ProxyHelper.executeMethod(httpClient, postMethod);
            result = postMethod.getResponseBodyAsString();
            //System.out.println("Result: " + result);
            System.out.println("...changed");
        } else {
            System.out.println("...not affected");
        }
    }

}

From source file:TestCookieDecode.java

/**
 * @param args//  w ww . j ava 2 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:com.leixl.easyframework.action.httpclient.TestHttpPost.java

public static void main(String[] args) {

    Map<String, Object> paramMap = new HashMap<String, Object>();
    paramMap.put("uid", 1);
    paramMap.put("desc",
            "?????");
    paramMap.put("payStatus", 1);

    //HttpConnUtils.postHttpContent(URL, paramMap);

    //HttpClient/*www  .jav a 2 s  .  c o  m*/
    HttpClient httpClient = new HttpClient();
    PostMethod postMethod = new PostMethod(URL);
    // ??
    NameValuePair[] data = { new NameValuePair("uid", "1"),
            new NameValuePair("desc",
                    "?????"),
            new NameValuePair("payStatus", "1") };
    // ?postMethod
    postMethod.setRequestBody(data);
    // postMethod
    int statusCode;
    try {
        statusCode = httpClient.executeMethod(postMethod);
        if (statusCode == HttpStatus.SC_OK) {
            StringBuffer contentBuffer = new StringBuffer();
            InputStream in = postMethod.getResponseBodyAsStream();
            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(in, postMethod.getResponseCharSet()));
            String inputLine = null;
            while ((inputLine = reader.readLine()) != null) {
                contentBuffer.append(inputLine);
                System.out.println("input line:" + inputLine);
                contentBuffer.append("/n");
            }
            in.close();

        } else if (statusCode == HttpStatus.SC_MOVED_PERMANENTLY
                || statusCode == HttpStatus.SC_MOVED_TEMPORARILY) {
            // ???
            Header locationHeader = postMethod.getResponseHeader("location");
            String location = null;
            if (locationHeader != null) {
                location = locationHeader.getValue();
                System.out.println("The page was redirected to:" + location);
            } else {
                System.err.println("Location field value is null.");
            }
        }
    } catch (HttpException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

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   ww  w .ja 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  2s .  c om*/
    // 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  w w .j  av  a 2 s  .com

    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:com.spun.util.ups.UPSUtils.java

/***********************************************************************/
public static UPSQuote[] getQuote(UPSConfig config, String reqbody) throws SAXException,
        ParserConfigurationException, FactoryConfigurationError, HttpException, IOException {
    HttpClient client = new HttpClient();
    PostMethod post = new PostMethod(UPS_URL);
    post.setRequestBody(reqbody);
    InputStream response = quoteRetriever.getResponse(client, post);
    UPSQuote[] quotes = extractQuotes(response);
    return quotes;
}

From source file:dk.statsbiblioteket.doms.licensemodule.integrationtest.HttpClientPoster.java

public static String postJSON(String url, String content) throws Exception {

    HttpClient client = new HttpClient();
    client.getParams().setParameter("http.useragent", "Dokumentleveringweb XML client");

    BufferedReader br = null;/*from   w  w  w  .ja v  a 2  s .  c  o m*/

    //TODO property
    PostMethod method = new PostMethod(url);

    method.addRequestHeader("Content-Type", "application/json;charset=UTF-8");
    method.setRequestBody(content); // How to do this a non-deprecated way?

    try {
        int httpCode = client.executeMethod(method);
        br = new BufferedReader(new InputStreamReader(method.getResponseBodyAsStream()));

        String readLine;
        StringBuilder response = new StringBuilder();
        while (((readLine = br.readLine()) != null)) {
            response.append(readLine);

        }
        return response.toString();

    } catch (Exception e) {
        throw e;
    } finally {
        method.releaseConnection();
        if (br != null)
            try {
                br.close();
            } catch (Exception fe) {
                fe.printStackTrace();
            }
    }

}