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:net.mumie.cocoon.msg.AbstractPostMessage.java

/**
 * Sends this message./*w w w  .  j  av  a  2  s. c om*/
 */

public boolean send() {
    final String METHOD_NAME = "send";
    this.logDebug(METHOD_NAME + " 1/3: Started");
    boolean success = true;

    MessageDestinationTable destinationTable = null;
    SimpleHttpClient httpClient = null;

    try {
        // Init services:
        destinationTable = (MessageDestinationTable) this.serviceManager.lookup(MessageDestinationTable.ROLE);
        httpClient = (SimpleHttpClient) this.serviceManager.lookup(SimpleHttpClient.ROLE);

        // Get destination:
        MessageDestination destination = destinationTable.getDestination(this.destinationName);

        // Create and setup a Http Post method object:
        PostMethod method = new PostMethod(destination.getURL());
        DefaultMethodRetryHandler retryHandler = new DefaultMethodRetryHandler();
        retryHandler.setRequestSentRetryEnabled(false);
        retryHandler.setRetryCount(3);
        method.setMethodRetryHandler(retryHandler);

        // Set login name and password:
        method.addParameter("name", destination.getLoginName());
        method.addParameter("password", destination.getPassword());

        // Specific setup:
        this.init(method, destination);

        // Execute method:
        try {
            if (httpClient.executeMethod(method) != HttpStatus.SC_OK) {
                this.logError(METHOD_NAME + ": Failed to send message: " + method.getStatusLine());
                success = false;
            }
            String response = new String(method.getResponseBody());
            if (response.trim().startsWith("ERROR")) {
                this.logError(METHOD_NAME + ": Failed to send message: " + response);
                success = false;
            }
            this.logDebug(METHOD_NAME + " 2/3: response = " + response);
        } finally {
            method.releaseConnection();
        }
    } catch (Exception exception) {
        this.logError(METHOD_NAME, exception);
        success = false;
    } finally {
        if (httpClient != null)
            this.serviceManager.release(httpClient);
        if (destinationTable != null)
            this.serviceManager.release(destinationTable);
    }

    this.logDebug(METHOD_NAME + " 3/3: Done. success = " + success);
    return success;
}

From source file:is.idega.block.finance.business.sp.SPDataInsert.java

/**
 * Sends a http post method to Sparisj to get the status of claims
 * /*from   www .  ja v  a2  s .com*/
 * @param bfm
 * @param groupId
 * @return
 */
private String sendGetClaimStatusRequest(BankFileManager bfm, String fromDate, String toDate) {
    HttpClient client = new HttpClient();
    PostMethod post = new PostMethod(POST_ANSWER_METHOD);
    String response = new String();
    try {
        post.addParameter("notendanafn", bfm.getUsername());
        post.addParameter("password", bfm.getPassword());
        post.addParameter("KtFelags", bfm.getClaimantSSN());
        post.addParameter("Reikningsnr", "");
        String claimantAccountId = bfm.getClaimantsAccountId();
        if (claimantAccountId != null && !claimantAccountId.equals("")) {
            if (claimantAccountId.length() < 3)
                claimantAccountId = zeroString.substring(0, 3 - claimantAccountId.length());
        } else {
            claimantAccountId = zeroString.substring(0, 3);
        }
        post.addParameter("Audkenni", claimantAccountId);
        post.addParameter("DagsFra", fromDate);// "20030701"
        post.addParameter("DagsTil", toDate);// "20040823"
        /*
         * Snidmat can be: 230 - print out 240 - Excel 250 - booking file 62
         * 251 - booking file 66 252 - XML
         */
        post.addParameter("Snidmat", "230");
        client.executeMethod(post);

        response = post.getResponseBodyAsString();

    } catch (HttpException e) {
        e.printStackTrace();
    } catch (IllegalArgumentException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        post.releaseConnection();
    }
    // System.out.println("response: " + response);
    return response;
}

From source file:com.autentia.mvn.plugin.changes.HttpRequest.java

/**
 * Send a GET method request to the given link using the configured HttpClient, possibly following redirects, and returns
 * the response as String.// w w w  . j a  v  a2s.  c o m
 * 
 * @param cl the HttpClient
 * @param link the URL
 * @throws HttpStatusException
 * @throws IOException
 */
public byte[] sendPostRequest(final HttpClient cl, final String link, final String parameters)
        throws HttpStatusException, IOException {
    try {
        final PostMethod pm = new PostMethod(link);

        if (parameters != null) {
            final String[] params = parameters.split("&");
            for (final String param : params) {
                final String[] pair = param.split("=");
                if (pair.length == 2) {
                    pm.addParameter(pair[0], pair[1]);
                }
            }
        }

        this.getLog().info("Downloading from Bugzilla at: " + link);

        cl.executeMethod(pm);

        final StatusLine sl = pm.getStatusLine();

        if (sl == null) {
            this.getLog().error("Unknown error validating link: " + link);

            throw new HttpStatusException("UNKNOWN STATUS");
        }

        // if we get a redirect, throws exception
        if (pm.getStatusCode() == HttpStatus.SC_MOVED_TEMPORARILY) {
            this.getLog().debug("Attempt to redirect ");
            throw new HttpStatusException("Attempt to redirect");
        }

        if (pm.getStatusCode() == HttpStatus.SC_OK) {
            final InputStream is = pm.getResponseBodyAsStream();
            final ByteArrayOutputStream baos = new ByteArrayOutputStream();
            final byte[] buff = new byte[256];
            int readed = is.read(buff);
            while (readed != -1) {
                baos.write(buff, 0, readed);
                readed = is.read(buff);
            }

            this.getLog().debug("Downloading from Bugzilla was successful");
            return baos.toByteArray();
        } else {
            this.getLog().warn("Downloading from Bugzilla failed. Received: [" + pm.getStatusCode() + "]");
            throw new HttpStatusException("WRONG STATUS");
        }
    } catch (final HttpException e) {
        if (this.getLog().isDebugEnabled()) {
            this.getLog().error("Error downloading issues from Bugzilla:", e);
        } else {
            this.getLog().error("Error downloading issues from Bugzilla url: " + e.getLocalizedMessage());

        }
        throw e;
    } catch (final IOException e) {
        if (this.getLog().isDebugEnabled()) {
            this.getLog().error("Error downloading issues from Bugzilla:", e);
        } else {
            this.getLog().error("Error downloading issues from Bugzilla. Cause is " + e.getLocalizedMessage());
        }
        throw e;
    }
}

From source file:edu.wustl.bulkoperator.client.BulkOperationServiceImpl.java

/**
 * This method will be called to logged in to the application.
 * @param url URL//from   w  w  w. ja v  a 2s  .  c o m
 * @param applicationUserName application user name.
 * @param applicationUserPassword application user password.
 * @param keyStoreLocation key store location.
 * @return Job Message.
 * @throws BulkOperationException BulkOperationException
 */
public JobMessage login(String url, String applicationUserName, String applicationUserPassword,
        String keyStoreLocation) throws BulkOperationException {
    setApplicationDetails(url, applicationUserName, applicationUserPassword, keyStoreLocation);
    JobMessage jobMessage = null;
    PostMethod postMethod = new PostMethod(url + "/BulkLogin.do");
    try {

        if (keyStoreLocation != null) {
            System.setProperty("javax.net.ssl.trustStore", keyStoreLocation);
        }
        postMethod.addParameter(USER_NAME, applicationUserName);
        postMethod.addParameter(PASSWORD, applicationUserPassword);
        client.executeMethod(postMethod);
        InputStream inputStream = (InputStream) postMethod.getResponseBodyAsStream();
        ObjectInputStream ois = new ObjectInputStream(inputStream);
        Object object = ois.readObject();
        jobMessage = (JobMessage) object;
        isLoggedIn = true;
    } catch (IOException e) {
        jobMessage = new JobMessage();
        jobMessage.setOperationSuccessfull(false);
        jobMessage.addMessage(ApplicationProperties.getValue("bulk.operation.client.error"));
    } catch (ClassNotFoundException e) {
        jobMessage = new JobMessage();
        jobMessage.setOperationSuccessfull(false);
        jobMessage.addMessage(ApplicationProperties.getValue("clz.not.found.error"));
    } finally {
        postMethod.releaseConnection();
    }
    return jobMessage;
}

From source file:ch.swing.gridcertlib.SLCSRequestor.java

/**
 * Request a certificate from the SLCS service and store the returned one.
 *
 * @throws org.glite.slcs.SLCSException//from  w  ww . j a v a2s.c  om
 */
public void requestSlcsCertificate() throws SLCSException {
    PostMethod postCertificateRequestMethod = new PostMethod(certificateRequestUrl_);
    postCertificateRequestMethod.addParameter("AuthorizationToken", authorizationToken_);
    postCertificateRequestMethod.addParameter("CertificateSigningRequest", certificateRequest_.getPEMEncoded());
    try {
        LOG.info("POST CSR: " + certificateRequestUrl_);
        int status = wsc_.executeMethod(postCertificateRequestMethod);
        LOG.debug(postCertificateRequestMethod.getStatusLine().toString());
        // check status
        if (status != 200) {
            LOG.error("SLCS certificate request failed: " + postCertificateRequestMethod.getStatusLine());
            throw new ServiceException(
                    "SLCS certificate request failed: " + postCertificateRequestMethod.getStatusLine());
        }
        // read response
        InputStream is = postCertificateRequestMethod.getResponseBodyAsStream();
        Source source = new Source(is);
        checkSLCSResponse(source, "SLCSCertificateResponse");
        parseSLCSCertificateResponse(source);
    } catch (IOException e) {
        final String message = "Failed to request certificate, I/O error: " + e.getMessage();
        LOG.error(message, e);
        throw new SLCSException(message, e);
    } finally {
        postCertificateRequestMethod.releaseConnection();
    }
}

From source file:is.idega.block.finance.business.kb.KBDataInsert.java

/**
 * Sends a http post method to KBBanki to get the status of claims
 * /*from w w  w  .ja va  2 s . co  m*/
 * @param bfm
 * @param groupId
 * @return
 */
private String sendGetClaimStatusRequest(BankFileManager bfm, String fromDate, String toDate) {
    HttpClient client = new HttpClient();
    PostMethod post = new PostMethod(POST_ANSWER_METHOD);
    String response = new String();
    try {
        post.addParameter("cguser", bfm.getUsername());
        post.addParameter("cgpass", bfm.getPassword());
        // post.addParameter("cgbnum", "64014");
        post.addParameter("cgdfra", fromDate);// "20030701"
        post.addParameter("cgdtil", toDate);// "20040823"
        post.addParameter("cgvisi", bfm.getClaimantsAccountId());
        post.addParameter("cgSvarskra", "on");
        client.executeMethod(post);

        response = post.getResponseBodyAsString();

    } catch (HttpException e) {
        e.printStackTrace();
    } catch (IllegalArgumentException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        post.releaseConnection();
    }
    // System.out.println("response: " + response);
    return response;
}

From source file:is.idega.block.finance.business.sp.SPDataInsertTest.java

/**
 * Sends a http post method to Sparisj to get the status of claims
 * //w w w.  j av a2s . c o m
 * @param bfm
 * @param groupId
 * @return
 */
private String sendGetClaimStatusRequest(BankFileManager bfm, int groupId, String fromDate, String toDate) {
    /*
     * Protocol easyhttps = new Protocol("https", new
     * EasySSLProtocolSocketFactory(), 443);
     */

    HttpClient client = new HttpClient();
    // client.getHostConfiguration().setHost(SITE, 443, easyhttps);
    PostMethod post = new PostMethod(SITE + POST_ANSWER_METHOD);

    String response = new String();
    try {
        post.addParameter("notendanafn", bfm.getUsername());
        post.addParameter("password", bfm.getPassword());
        post.addParameter("KtFelags", bfm.getClaimantSSN());
        post.addParameter("Reikningsnr", "");
        String claimantAccountId = bfm.getClaimantsAccountId();
        if (claimantAccountId != null && !claimantAccountId.equals("")) {
            if (claimantAccountId.length() < 3)
                claimantAccountId = zeroString.substring(0, 3 - claimantAccountId.length());
        } else {
            claimantAccountId = zeroString.substring(0, 3);
        }
        post.addParameter("Audkenni", claimantAccountId);
        post.addParameter("DagsFra", fromDate);// "20030701"
        post.addParameter("DagsTil", toDate);// "20040823"
        /*
         * Snidmat can be: 230 - print out 240 - Excel 250 - booking file 62
         * 251 - booking file 66 252 - XML
         */
        post.addParameter("Snidmat", "230");
        client.executeMethod(post);

        response = post.getResponseBodyAsString();

    } catch (HttpException e) {
        e.printStackTrace();
    } catch (IllegalArgumentException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        post.releaseConnection();
    }
    // System.out.println("response: " + response);
    return response;
}

From source file:net.peacesoft.nutch.crawl.ReSolrWriter.java

public void postHttp(String httpServer, NutchDocument doc) {
    try {/*from   ww w  . j  a  va  2s .c  o  m*/
        HttpClient client = new HttpClient();
        PostMethod method = new PostMethod(httpServer);
        Object tmp = doc.getFieldValue("myid");
        if (LOG.isInfoEnabled()) {
            LOG.info("Post content id " + tmp.toString() + "to http server: " + httpServer);
        }
        if (tmp != null) {
            method.addParameter("CrawlerContent[id]", tmp.toString());
        }
        tmp = doc.getFieldValue("title");
        if (tmp != null) {
            method.addParameter("CrawlerContent[title]", Base64.encodeBase64String(tmp.toString().getBytes()));
        }
        tmp = doc.getFieldValue("categoryId");
        if (tmp != null) {
            method.addParameter("CrawlerContent[categoryId]",
                    Base64.encodeBase64String(tmp.toString().getBytes()));
        }
        tmp = doc.getFieldValue("categoryChildId");
        if (tmp != null) {
            method.addParameter("CrawlerContent[categoryChildId]",
                    Base64.encodeBase64String(tmp.toString().getBytes()));
        }
        tmp = doc.getFieldValue("content");
        if (tmp != null) {
            method.addParameter("CrawlerContent[content]",
                    Base64.encodeBase64String(tmp.toString().getBytes()));
        }
        tmp = doc.getFieldValue("contentHtml");
        if (tmp != null) {
            method.addParameter("CrawlerContent[contentHtml]", tmp.toString());
        }
        tmp = doc.getFieldValue("location");
        if (tmp != null) {
            method.addParameter("CrawlerContent[Location]",
                    Base64.encodeBase64String(tmp.toString().getBytes()));
        }
        tmp = doc.getFieldValue("tstamp");
        if (tmp != null) {
            method.addParameter("CrawlerContent[createDate]",
                    Base64.encodeBase64String(tmp.toString().getBytes()));
        }
        tmp = doc.getFieldValue("domain");
        if (tmp != null) {
            method.addParameter("CrawlerContent[domain]", tmp.toString());
        }
        tmp = doc.getFieldValue("url");
        if (tmp != null) {
            method.addParameter("CrawlerContent[url]", Base64.encodeBase64String(tmp.toString().getBytes()));
        }
        tmp = doc.getFieldValue("mobile");
        if (tmp != null) {
            method.addParameter("CrawlerContent[mobile]", tmp.toString());
        }
        tmp = doc.getFieldValue("address");
        if (tmp != null) {
            method.addParameter("CrawlerContent[address]",
                    Base64.encodeBase64String(tmp.toString().getBytes()));
        }
        client.executeMethod(method);
        byte[] data = method.getResponseBody();
        toFile(doc.getFieldValue("segment").toString() + ".html", data);
    } catch (Exception ex) {
        LOG.warn("Error when post data to server: " + httpServer, ex);
    }
}

From source file:com.denimgroup.threadfix.remote.HttpRestUtils.java

private void addApiKey(PostMethod post) {
    if (propertiesManager.getKey() == null) {
        throw new IllegalStateException(
                "Please set your key before using this tool. Use the -s key <key> option.");
    } else {//from w  w  w.j av a  2 s . c  o  m
        post.addParameter("apiKey", propertiesManager.getKey());
    }
}

From source file:greenfoot.export.mygame.MyGameClient.java

public final MyGameClient submit(String hostAddress, String uid, String password, String jarFileName,
        File sourceFile, File screenshotFile, int width, int height, ScenarioInfo info)
        throws UnknownHostException, IOException {
    String gameName = info.getTitle();
    String shortDescription = info.getShortDescription();
    String longDescription = info.getLongDescription();
    String updateDescription = info.getUpdateDescription();
    String gameUrl = info.getUrl();

    HttpClient httpClient = getHttpClient();
    httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(20 * 1000); // 20s timeout

    // Authenticate user and initiate session
    PostMethod postMethod = new PostMethod(hostAddress + "account/authenticate");

    postMethod.addParameter("user[username]", uid);
    postMethod.addParameter("user[password]", password);

    int response = httpClient.executeMethod(postMethod);

    if (response == 407 && listener != null) {
        // proxy auth required
        String[] authDetails = listener.needProxyAuth();
        if (authDetails != null) {
            String proxyHost = httpClient.getHostConfiguration().getProxyHost();
            int proxyPort = httpClient.getHostConfiguration().getProxyPort();
            AuthScope authScope = new AuthScope(proxyHost, proxyPort);
            Credentials proxyCreds = new UsernamePasswordCredentials(authDetails[0], authDetails[1]);
            httpClient.getState().setProxyCredentials(authScope, proxyCreds);

            // Now retry:
            response = httpClient.executeMethod(postMethod);
        }/* ww w .ja  va 2s  . c  om*/
    }

    if (response > 400) {
        error(Config.getString("export.publish.errorResponse") + " - " + response);
        return this;
    }

    // Check authentication result
    if (!handleResponse(postMethod)) {
        return this;
    }

    // Send the scenario and associated info
    List<String> tagsList = info.getTags();
    boolean hasSource = sourceFile != null;
    //determining the number of parts to send through
    //use a temporary map holder
    Map<String, String> partsMap = new HashMap<String, String>();
    if (info.isUpdate()) {
        partsMap.put("scenario[update_description]", updateDescription);
    } else {
        partsMap.put("scenario[long_description]", longDescription);
        partsMap.put("scenario[short_description]", shortDescription);
    }
    int size = partsMap.size();

    if (screenshotFile != null) {
        size = size + 1;
    }

    //base number of parts is 6
    int counter = 6;
    Part[] parts = new Part[counter + size + tagsList.size() + (hasSource ? 1 : 0)];
    parts[0] = new StringPart("scenario[title]", gameName, "UTF-8");
    parts[1] = new StringPart("scenario[main_class]", "greenfoot.export.GreenfootScenarioViewer", "UTF-8");
    parts[2] = new StringPart("scenario[width]", "" + width, "UTF-8");
    parts[3] = new StringPart("scenario[height]", "" + height, "UTF-8");
    parts[4] = new StringPart("scenario[url]", gameUrl, "UTF-8");
    parts[5] = new ProgressTrackingPart("scenario[uploaded_data]", new File(jarFileName), this);
    Iterator<String> mapIterator = partsMap.keySet().iterator();
    String key = "";
    String obj = "";
    while (mapIterator.hasNext()) {
        key = mapIterator.next().toString();
        obj = partsMap.get(key).toString();
        parts[counter] = new StringPart(key, obj, "UTF-8");
        counter = counter + 1;
    }

    if (hasSource) {
        parts[counter] = new ProgressTrackingPart("scenario[source_data]", sourceFile, this);
        counter = counter + 1;
    }
    if (screenshotFile != null) {
        parts[counter] = new ProgressTrackingPart("scenario[screenshot_data]", screenshotFile, this);
        counter = counter + 1;
    }

    int tagNum = 0;
    for (Iterator<String> i = tagsList.iterator(); i.hasNext();) {
        parts[counter] = new StringPart("scenario[tag" + tagNum++ + "]", i.next());
        counter = counter + 1;
    }

    postMethod = new PostMethod(hostAddress + "upload-scenario");
    postMethod.setRequestEntity(new MultipartRequestEntity(parts, postMethod.getParams()));

    response = httpClient.executeMethod(postMethod);
    if (response > 400) {
        error(Config.getString("export.publish.errorResponse") + " - " + response);
        return this;
    }

    if (!handleResponse(postMethod)) {
        return this;
    }

    // Done.
    listener.uploadComplete(new PublishEvent(PublishEvent.STATUS));

    return this;
}