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

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

Introduction

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

Prototype

public void addParameter(String paramString1, String paramString2) throws IllegalArgumentException 

Source Link

Usage

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

/**
 * @param submitUserFile/*from  www.  j a  v  a 2s .c om*/
 * @param courseKey
 * @param projectNumber
 * @param authenticationType
 * @param baseURL
 * @throws IOException
 * @throws UnsupportedEncodingException
 * @throws URISyntaxException
 * @throws HttpException
 */
public static void createSubmitUser(File submitUserFile, String courseKey, String projectNumber,
        String authenticationType, String baseURL)
        throws IOException, UnsupportedEncodingException, URISyntaxException, HttpException {
    PrintWriter newUserProjectFile;
    if (authenticationType.equals("openid")) {
        String[] result = getSubmitUserForOpenId(courseKey, projectNumber, baseURL);
        String classAccount = result[0];
        String onetimePassword = result[1];
        newUserProjectFile = new PrintWriter(new FileWriter(submitUserFile));
        newUserProjectFile.println("classAccount=" + classAccount);
        newUserProjectFile.println("oneTimePassword=" + onetimePassword);
    } else {
        String loginName, password;

        Console console = System.console();

        System.out.println("Please enter your LDAP username and password");
        System.out.print("LDAP username: ");
        loginName = console.readLine();
        System.out.println("Password: ");
        password = new String(console.readPassword());
        System.out.println("Thanks!");
        System.out.println("Preparing for submission. Please wait...");

        String url = baseURL + "/eclipse/NegotiateOneTimePassword";
        PostMethod post = new PostMethod(url);

        post.addParameter("loginName", loginName);
        post.addParameter("password", password);

        post.addParameter("courseKey", courseKey);
        post.addParameter("projectNumber", projectNumber);

        HttpClient client = new HttpClient();
        client.setConnectionTimeout(HTTP_TIMEOUT);

        // System.out.println("Preparing to execute method");
        int status = client.executeMethod(post);
        // System.out.println("Post finished with status: " +status);

        if (status != HttpStatus.SC_OK) {
            throw new HttpException(
                    "Unable to negotiate one-time password with the server: " + post.getResponseBodyAsString());
        }

        InputStream inputStream = post.getResponseBodyAsStream();
        BufferedReader userStream = new BufferedReader(new InputStreamReader(inputStream));
        newUserProjectFile = new PrintWriter(new FileWriter(submitUserFile));
        while (true) {
            String line = userStream.readLine();
            if (line == null)
                break;
            // System.out.println(line);
            newUserProjectFile.println(line);
        }
        userStream.close();
    }
    newUserProjectFile.close();
    if (!submitUserFile.canRead()) {
        System.out.println("Can't generate or access " + submitUserFile);
        System.exit(1);
    }
}

From source file:mesquite.tol.lib.BaseHttpRequestMaker.java

public static boolean postToServer(String s, String URI, StringBuffer response) {
    HttpClient client = new HttpClient();
    PostMethod method = new PostMethod(URI);
    method.addParameter("OS", StringEscapeUtils
            .escapeHtml(System.getProperty("os.name") + "\t" + System.getProperty("os.version")));
    method.addParameter("JVM", StringEscapeUtils
            .escapeHtml(System.getProperty("java.version") + "\t" + System.getProperty("java.vendor")));
    NameValuePair post = new NameValuePair();
    post.setName("post");
    post.setValue(StringEscapeUtils.escapeHtml(s));
    method.addParameter(post);/*  www .j  a  va2  s .c o m*/

    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(3, false));

    return executeMethod(client, method, response);
}

From source file:ec.edu.ucuenca.dcc.sld.HttpUtils.java

public static synchronized String Http2_(String s, Map<String, String> mp) throws SQLException, IOException {
    String resp = "";
    HttpClient client = new HttpClient();
    PostMethod method = new PostMethod(s);
    method.getParams().setContentCharset("utf-8");
    //Add any parameter if u want to send it with Post req.
    for (Entry<String, String> mcc : mp.entrySet()) {
        method.addParameter(mcc.getKey(), mcc.getValue());
    }/* w  ww.ja  v  a 2  s  .  c o m*/
    int statusCode = client.executeMethod(method);
    if (statusCode != -1) {
        InputStream in = method.getResponseBodyAsStream();
        final Scanner reader = new Scanner(in, "UTF-8");
        while (reader.hasNextLine()) {
            final String line = reader.nextLine();
            resp += line + "\n";
        }
        reader.close();
    }
    return resp;
}

From source file:dept_integration.Dept_Integchalan.java

public static String doSend(String STATUS, String TRANS_DATE, String TRANSID, String BANK_REFNO,
        String BANK_NAME, String CIN) throws Exception {
    String SCODE = "ihSkaRaA";
    String url = "http://wsdl.jhpolice.gov.in/smsresponse.php";
    String result = null;/*from w w w . j a va 2s.c om*/
    HttpClient client = null;
    PostMethod method = null;
    client = new HttpClient(new MultiThreadedHttpConnectionManager());

    method = new PostMethod(url);
    // method.addRequestHeader("Content-Type","application/xml");

    method.addParameter("STATUS", STATUS);
    // method.addParameter("signature",URLEncoder.encode(b,"UTF-8"));
    method.addParameter("TRANS_DATE", TRANS_DATE);
    method.addParameter("TRANSID", TRANSID);
    method.addParameter("BANK_REFNO", BANK_REFNO);
    method.addParameter("BANK_NAME", BANK_NAME);
    method.addParameter("CIN", CIN);
    method.addParameter("SCODE", SCODE);

    try {
        int statusCode = client.executeMethod(method);
        // System.out.println("lll"+method.getStatusLine().toString());
        if (statusCode == -1) {
            result = "N";
            System.err.println("HttpError: " + method.getStatusLine());
        } else {
            result = method.getResponseBodyAsString();
            System.out.println(result);
            //result= result.indexOf(""+mobile_no)==-1 ? "N" : "Y";
        }
    } catch (Exception e) {

        e.printStackTrace();

        System.err.println("Fatal protocol violation: " + e.getMessage());
        throw e;

    }

    finally {
        method.abort();
        method.releaseConnection();

    }

    return result;
}

From source file:edu.ucsb.nceas.metacat.util.RequestUtil.java

/**
 * Post a request and return the response body
 * /*  www . j a  v  a 2s  .co  m*/
 * @param httpClient
 *            The HttpClient to use in the post.  This is passed in because
  *            the same client may be used in several posts
 * @param url
 *            the url to post to
 * @param paramMap
 *            map of parameters to add to the post
 * @returns a string holding the response body
 */
public static String post(HttpClient httpClient, String url, HashMap<String, String> paramMap)
        throws IOException, HttpException {

    PostMethod method = new PostMethod(url);

    // Configure the form parameters
    if (paramMap != null) {
        Set<String> paramNames = paramMap.keySet();
        for (String paramName : paramNames) {
            method.addParameter(paramName, paramMap.get(paramName));
        }
    }

    // Execute the POST method
    int statusCode = httpClient.executeMethod(method);
    if (statusCode != -1) {
        String contents = method.getResponseBodyAsString();
        method.releaseConnection();
        return (contents);
    }

    return null;
}

From source file:ec.edu.ucuenca.dcc.sld.HttpUtils.java

public static synchronized String Http2(String s, Map<String, String> mp) throws SQLException, IOException {
    String resp = "";
    HttpClient client = new HttpClient();
    PostMethod method = new PostMethod(s);
    method.getParams().setContentCharset("utf-8");

    client.getParams().setParameter("api-key", "58ef39e0-b91a-11e6-a057-97f4c970893c");
    client.getParams().setParameter("Content-Type", "application/json");

    //Add any parameter if u want to send it with Post req.
    for (Entry<String, String> mcc : mp.entrySet()) {
        method.addParameter(mcc.getKey(), mcc.getValue());
    }//from  w w w  . j  a v  a 2 s  .c om

    int statusCode = client.executeMethod(method);

    if (statusCode != -1) {
        InputStream in = method.getResponseBodyAsStream();
        final Scanner reader = new Scanner(in, "UTF-8");
        while (reader.hasNextLine()) {
            final String line = reader.nextLine();
            resp += line + "\n";
        }
        reader.close();

    }

    return resp;
}

From source file:net.duckling.ddl.web.controller.AttachmentController.java

public static String getClbToken(int docId, int version, Properties properties) {
    HttpClient client = getHttpClient();
    PostMethod method = new PostMethod(getClbTokenUrl(properties));
    method.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "utf-8");
    method.addParameter("appname", properties.getProperty("duckling.clb.aone.user"));
    method.addParameter("docid", docId + "");
    method.addParameter("version", version + "");
    try {/*from   ww w .  j av  a2  s .  c  o  m*/
        method.addParameter("password",
                Base64.encodeBytes(properties.getProperty("duckling.clb.aone.password").getBytes("utf-8")));
    } catch (IllegalArgumentException | UnsupportedEncodingException e) {

    }
    try {
        int status = client.executeMethod(method);
        String responseString = null;
        if (status < 400) {
            responseString = method.getResponseBodyAsString();
            org.json.JSONObject j = new org.json.JSONObject(responseString);
            Object st = j.get("status");
            if ("failed".equals(st)) {
                LOG.error("?clb token?");
                return null;
            } else {
                return j.get("pf").toString();
            }
        } else {
            LOG.error("STAUTS:" + status + ";MESSAGE:" + responseString);
        }
    } catch (HttpException e) {
        LOG.error("", e);
    } catch (IOException e) {
        LOG.error("", e);
    } catch (ParseException e) {
        LOG.error("", e);
    }
    return null;
}

From source file:com.zimbra.cs.datasource.DataSourceManager.java

public static void refreshOAuthToken(DataSource ds) {
    PostMethod postMethod = null;
    try {/*from  w  w w . j av  a  2s .c o m*/
        postMethod = new PostMethod(ds.getOauthRefreshTokenUrl());
        postMethod.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        postMethod.addParameter(CLIENT_ID, ds.getOauthClientId());
        postMethod.addParameter(CLIENT_SECRET, ds.getDecryptedOAuthClientSecret());
        postMethod.addParameter(REFRESH_TOKEN, ds.getOauthRefreshToken());
        postMethod.addParameter(GRANT_TYPE, REFRESH_TOKEN);

        HttpClient httpClient = ZimbraHttpConnectionManager.getExternalHttpConnMgr().getDefaultHttpClient();
        int status = httpClient.executeMethod(postMethod);
        if (status == HttpStatus.SC_OK) {
            ZimbraLog.datasource.info("Refreshed oauth token status=%d", status);
            JSONObject response = new JSONObject(postMethod.getResponseBodyAsString());
            String oauthToken = response.getString(ACCESS_TOKEN);
            Map<String, Object> attrs = new HashMap<String, Object>();
            attrs.put(Provisioning.A_zimbraDataSourceOAuthToken,
                    DataSource.encryptData(ds.getId(), oauthToken));
            Provisioning provisioning = Provisioning.getInstance();
            provisioning.modifyAttrs(ds, attrs);
        } else {
            ZimbraLog.datasource.info("Could not refresh oauth token status=%d", status);
        }
    } catch (Exception e) {
        ZimbraLog.datasource.warn("Exception while refreshing oauth token", e);
    } finally {
        if (postMethod != null) {
            postMethod.releaseConnection();
        }
    }
}

From source file:ac.elements.io.Signature.java

/**
 * Gets the XML response as a string./*from w  ww  . ja  v  a  2 s  .  co m*/
 * 
 * @param keyValues
 *            the keyValues pairs
 * @param id
 *            the id
 * @param key
 *            the key
 * 
 * @return the XML response as a string
 */
public static String getXMLResponse(final Map<String, String> keyValues, String id, String key) {

    Map<String, String> parameters;
    try {
        parameters = Signature.getParameters(keyValues, id, key);
    } catch (SignatureException se) {
        se.printStackTrace();
        throw new RuntimeException("CredentialsNotFound: Please make sure " + "that the file "
                + "'aws.properties' is located in the classpath " + "(usually "
                + "$TOMCAT_HOME/webapps/mysimpledb/WEB-INF/classes" + ") of the java virtual machine. "
                + "This file should " + "define your AWSAccessKeyId and SecretAccessKey.");
    }
    int status = -1;
    String response = null;

    PostMethod method = new PostMethod(SERVICE_URL);

    for (Entry<String, String> entry : parameters.entrySet()) {
        method.addParameter(entry.getKey(), entry.getValue());
    }

    String en = null;
    try {

        /* Set content type and encoding */
        method.addRequestHeader("Content-Type",
                "application/x-www-form-urlencoded; charset=" + DEFAULT_ENCODING.toLowerCase());
        boolean shouldRetry = true;
        int retries = 0;
        do {
            // log.debug("Sending Request to host: " + SERVICE_URL);

            try {

                /* Submit request */
                status = Signature.httpClient.executeMethod(method);

                /* Consume response stream */
                response = getResponsBodyAsString(method.getResponseBodyAsStream());

                if (status == HttpStatus.SC_OK) {
                    shouldRetry = false;
                    // log.debug("Received Response. Status: " + status + ".
                    // " +
                    // "Response Body: " + responseBodyString);

                } else {
                    // log.debug("Received Response. Status: " + status + ".
                    // " +
                    // "Response Body: " + responseBodyString);

                    if ((status == HttpStatus.SC_INTERNAL_SERVER_ERROR
                            || status == HttpStatus.SC_SERVICE_UNAVAILABLE) && pauseIfRetryNeeded(++retries)) {
                        shouldRetry = true;
                    } else {
                        shouldRetry = false;
                    }
                }
            } catch (ConnectException ce) {
                shouldRetry = false;
                en =

                        "ConnectException: This webapp is not able to " + "connect, a likely cause is your "
                                + "firewall settings, please double check.";

            } catch (UnknownHostException uhe) {
                shouldRetry = false;
                en =

                        "UnknownHostException: This webapp is not able to " + "connect, to sdb.amazonaws.com "
                                + "please check connection and your " + "firewall settings.";

            } catch (IOException ioe) {

                ++retries;
                log.error("Caught IOException: ", ioe);
                ioe.printStackTrace();

            } catch (Exception e) {
                ++retries;
                log.error("Caught Exception: ", e);
                e.printStackTrace();
            } finally {
                method.releaseConnection();
            }
            // if (shouldRetry && retries == 1) {
            // concurrentRetries++;
            // log.warn("concurrentRetries: " + concurrentRetries);
            // }
            // if (concurrentRetries >= 1) {
            // StatementAsync.throttleDown();
            // } else {
            // StatementAsync.throttleUp();
            // }
        } while (shouldRetry);
        // if (retries > 0 && concurrentRetries > 0)
        // concurrentRetries--;
    } catch (Exception e) {
        log.error("Caught Exception: ", e);
        e.printStackTrace();
    }
    if (en != null) {
        throw new RuntimeException(en);
    }
    if (response.indexOf("<Code>InvalidClientTokenId</Code>") != -1) {

        throw new RuntimeException("InvalidClientTokenId: The AWS Access Key Id you provided "
                + "does not exist in Amazons records. The file " + "aws.properties should define your "
                + "AWSAccessKeyId and SecretAccessKey.");

    } else if (response.indexOf("<Code>SignatureDoesNotMatch</Code>") != -1) {

        throw new RuntimeException("SignatureDoesNotMatch: The request signature we "
                + "calculated does not match the signature you " + "provided. Check your Secret Access Key "
                + "and signing method. Consult the service " + "documentation for details.");
    } else if (response.indexOf("<Code>AuthFailure</Code>") != -1) {

        throw new RuntimeException("AuthFailure: AWS was not able to validate the provided "
                + "access credentials. This usually means you do " + "not have a simple db account. "
                + "Go to <a href=\"" + "http://aws.amazon.com/simpledb/\">Amazon's "
                + "Simple DB</a> page and create an account, if " + "you do not have one at this moment.");
    } else if (response.indexOf("<Errors>") != -1) {

        log.error("Found keyword error in response:\n" + response);
        log.error("Key value pairs sent:\n" + keyValues);

    }
    return response;

}

From source file:edu.umd.cs.eclipse.courseProjectManager.TurninProjectAction.java

private static InputStream getSubmitUserFileFromServer(String loginName, String password,
        Properties allProperties) throws IOException, HttpException {
    String url = allProperties.getProperty("baseURL");
    url += "/eclipse/NegotiateOneTimePassword";
    // System.out.println(url);
    // Debug.print("url: " +url);
    PostMethod post = new PostMethod(url);
    post.addParameter("loginName", loginName);
    post.addParameter("password", password);

    addParameter(post, "courseKey", allProperties);
    addParameter(post, "projectNumber", allProperties);
    post.addParameter("submitClientVersion", AutoCVSPlugin.getPlugin().getVersion());

    HttpClient client = new HttpClient();
    client.setConnectionTimeout(5000);//ww w  .j a  v  a  2s .  c o m

    // System.out.println("Preparing to execute method");
    int status = client.executeMethod(post);
    // System.out.println("Post finished with status: " +status);

    if (status != HttpStatus.SC_OK) {
        throw new HttpException(
                "Unable to negotiate one-time password with the server: " + post.getResponseBodyAsString());
    }

    return post.getResponseBodyAsStream();
}