Example usage for org.apache.commons.httpclient NameValuePair NameValuePair

List of usage examples for org.apache.commons.httpclient NameValuePair NameValuePair

Introduction

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

Prototype

public NameValuePair(String name, String value) 

Source Link

Document

Constructor.

Usage

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// w w  w. 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:com.discursive.jccook.httpclient.QueryStringExample.java

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

    String url = "http://www.discursive.com/cgi-bin/jccook/param_list.cgi";

    // Set the Query String with setQueryString()
    HttpMethod method = new GetMethod(url);
    method.setQueryString(URIUtil.encodeQuery("test1=O'Reilly&blah=Whoop"));
    System.out.println("With Query String: " + method.getURI());
    client.executeMethod(method);//from   ww  w  . ja  va  2 s  . c  o  m
    System.out.println("Response:\n " + method.getResponseBodyAsString());
    method.releaseConnection();

    // Set query string with name value pair objects
    method = new GetMethod(url);
    NameValuePair pair = new NameValuePair("test2", URIUtil.encodeQuery("One & Two"));
    NameValuePair pair2 = new NameValuePair("param2", URIUtil.encodeQuery("TSCM"));
    NameValuePair[] pairs = new NameValuePair[] { pair, pair2 };
    method.setQueryString(pairs);
    System.out.println("With NameValuePairs: " + method.getURI());
    client.executeMethod(method);
    System.out.println("Response:\n " + method.getResponseBodyAsString());
    method.releaseConnection();
}

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);/* w w w . jav a 2 s  .  c o  m*/
    String response = method.getResponseBodyAsString();
    System.out.println(response);

    method.releaseConnection();
}

From source file:TestCookieDecode.java

/**
 * @param args/* w ww. j av  a 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:com.francetelecom.admindm.changedustate.callviaacs.CallChangeDUStateUninstallCapabilityOnEdgeAcs.java

/**
 * @param args/*ww w. j a v a 2 s .  co m*/
 */
public static void main(final String[] args) {
    HttpClient client = new HttpClient();
    // client.getHostConfiguration().setProxy("", );

    String host = null;
    String port = null;
    String address = "http://" + host + ":" + port + "/edge/api/";

    String acsUsername = null;
    String acsPassword = null;

    if (host == null || port == null || acsUsername == null || acsPassword == null) {
        throw new InvalidParameterException("Fill host: " + host + ", port: " + port + ", acsUsername: "
                + acsUsername + ", and acsPassword: " + acsPassword + ".");
    }

    String realm = "NBBS_API_Realm";

    AuthScope authscope = new AuthScope(host, Integer.parseInt(port), realm);

    // client.getState().setCredentials(realm, host,
    // new UsernamePasswordCredentials(acsUsername, acsPassword));

    client.getState().setCredentials(authscope, new UsernamePasswordCredentials(acsUsername, acsPassword));

    PostMethod post = null;

    // -----
    // ----- Execution de la capability : changeDUStateUninstall
    // -----

    post = new PostMethod(address + "capability/execute");

    post.addParameter(new NameValuePair("deviceId", "10003"));
    post.addParameter(new NameValuePair("timeoutMs", "60000"));
    post.addParameter(new NameValuePair("capability", "\"changeDUStateUninstall\""));

    // UUID: string
    // Version: string
    // ExecutionEnvRef: String

    JSONObject object = new JSONObject();
    object.put("UUID", "45");
    object.put("Version", "2.2.0");
    object.put("ExecutionEnvRef", "ExecutionEnvRef_value");
    post.addParameter(new NameValuePair("input", object.toString()));

    post.setDoAuthentication(true);

    // post.addParameter(new NameValuePair("deviceId", "60001"));

    // -----
    // ----- Partie commune : Execution du post
    // -----

    try {
        int status = client.executeMethod(post);
        System.out.println("status: " + status);
        String resp = post.getResponseBodyAsString();
        System.out.println("resp: " + resp);
    } catch (HttpException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        // release any connection resources used by the method
        post.releaseConnection();
    }
}

From source file:com.francetelecom.admindm.changedustate.callviaacs.CallChangeDUStateUpdateCapabilityOnEdgeAcs.java

/**
 * @param args//from  www.  ja va2 s.  c  o m
 */
public static void main(final String[] args) {
    HttpClient client = new HttpClient();
    // client.getHostConfiguration().setProxy("", );

    String host = null;
    String port = null;
    String address = "http://" + host + ":" + port + "/edge/api/";

    String acsUsername = null;
    String acsPassword = null;

    if (host == null || port == null || acsUsername == null || acsPassword == null) {
        throw new InvalidParameterException("Fill host: " + host + ", port: " + port + ", acsUsername: "
                + acsUsername + ", and acsPassword: " + acsPassword + ".");
    }

    String realm = "NBBS_API_Realm";

    AuthScope authscope = new AuthScope(host, Integer.parseInt(port), realm);

    // client.getState().setCredentials(realm, host,
    // new UsernamePasswordCredentials(acsUsername, acsPassword));

    client.getState().setCredentials(authscope, new UsernamePasswordCredentials(acsUsername, acsPassword));

    PostMethod post = null;

    // -----
    // ----- Execution de la capability : changeDUStateUpdate
    // -----

    post = new PostMethod(address + "capability/execute");

    post.addParameter(new NameValuePair("deviceId", "10003"));
    post.addParameter(new NameValuePair("timeoutMs", "60000"));
    post.addParameter(new NameValuePair("capability", "\"changeDUStateUpdate\""));

    // UUID: string
    // Version: string
    // URL: string
    // Username: string
    // Password: string

    JSONObject object = new JSONObject();
    object.put("UUID", "45");
    object.put("Version", "1.0.0");
    object.put("URL", "http://127.0.0.1:8085/a/org.apache.felix.http.jetty-2.2.0.jar");
    object.put("Username", "Username_value");
    object.put("Password", "Password_value");
    post.addParameter(new NameValuePair("input", object.toString()));

    post.setDoAuthentication(true);

    // post.addParameter(new NameValuePair("deviceId", "60001"));

    // -----
    // ----- Partie commune : Execution du post
    // -----

    try {
        int status = client.executeMethod(post);
        System.out.println("status: " + status);
        String resp = post.getResponseBodyAsString();
        System.out.println("resp: " + resp);
    } catch (HttpException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        // release any connection resources used by the method
        post.releaseConnection();
    }
}

From source file:com.francetelecom.admindm.changedustate.callviaacs.CallChangeDUStateInstallCapabilityOnEdgeAcs.java

/**
 * @param args/*ww  w  . j a v  a  2 s  .c  om*/
 */
public static void main(final String[] args) {
    HttpClient client = new HttpClient();
    // client.getHostConfiguration().setProxy("", );

    String host = null;
    String port = null;
    String address = "http://" + host + ":" + port + "/edge/api/";

    String acsUsername = null;
    String acsPassword = null;

    if (host == null || port == null || acsUsername == null || acsPassword == null) {
        throw new InvalidParameterException("Fill host: " + host + ", port: " + port + ", acsUsername: "
                + acsUsername + ", and acsPassword: " + acsPassword + ".");
    }

    String realm = "NBBS_API_Realm";

    AuthScope authscope = new AuthScope(host, Integer.parseInt(port), realm);

    // client.getState().setCredentials(realm, host,
    // new UsernamePasswordCredentials(acsUsername, acsPassword));

    client.getState().setCredentials(authscope, new UsernamePasswordCredentials(acsUsername, acsPassword));

    PostMethod post = null;

    // -----
    // ----- Execution de la capability : changeDUStateInstall
    // -----

    post = new PostMethod(address + "capability/execute");

    post.addParameter(new NameValuePair("deviceId", "10003"));
    post.addParameter(new NameValuePair("timeoutMs", "60000"));
    post.addParameter(new NameValuePair("capability", "\"changeDUStateInstall\""));

    // URL: string
    // UUID: string
    // Username: string
    // Password: string
    // ExecutionEnvRef: string

    JSONObject object = new JSONObject();
    object.put("URL", "http://127.0.0.1:8085/a/org.apache.felix.http.jetty-1.0.0.jar");
    // object.put("UUID", "UUID_value");
    object.put("Username", "Username_value");
    object.put("Password", "Password_value");
    object.put("ExecutionEnvRef", "ExecutionEnvRef_value");
    post.addParameter(new NameValuePair("input", object.toString()));

    post.setDoAuthentication(true);

    // post.addParameter(new NameValuePair("deviceId", "60001"));

    // -----
    // ----- Partie commune : Execution du post
    // -----

    try {
        int status = client.executeMethod(post);
        System.out.println("status: " + status);
        String resp = post.getResponseBodyAsString();
        System.out.println("resp: " + resp);

        // 10 avr. 2013 10:09:23
        // org.apache.commons.httpclient.auth.AuthChallengeProcessor
        // selectAuthScheme
        // INFO: basic authentication scheme selected
        // status: 200
        // resp: "executed: changeDUStateInstall: {Password=Password_value,
        // Username=Username_value, ExecutionEnvRef=ExecutionEnvRef_value,
        // URL=http:\/\/archive.apache.org\/dist\/felix\/org.apache.felix.http.jetty-1.0.0.jar},
        // resp: com.netopia.nbbs.tr69.msg.ChangeDUStateResponse@2db81edf"

    } catch (HttpException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        // release any connection resources used by the method
        post.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 ww . j ava 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 v  a  2 s  . 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: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);/*www. ja v a2  s  .  co  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);
}