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:Interface.FramePrincipal.java

private void bt_uplActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bt_uplActionPerformed

    File diretorio = new File(dir_arq.getText());
    File file = new File(dir_arq.getText() + "/" + nom_arq.getText());

    if (!diretorio.exists()) {
        JOptionPane.showMessageDialog(null, "Informe um diretrio vlido!");
    } else if (!file.exists() || "".equals(nom_arq.getText())) {
        JOptionPane.showMessageDialog(null, "Informe um arquivo vlido!");
    } else {/*  w  w  w .  j a  va 2 s . c  o  m*/
        try {
            //////////////////////////////////////// Validar tamanho de arquivo/////////////////////////////////////////////////               
            RandomAccessFile arquivo = new RandomAccessFile(dir_arq.getText() + "/" + nom_arq.getText(), "r");
            long tamanho = arquivo.length();

            if (tamanho >= 104857600) {
                JOptionPane.showMessageDialog(null, "Arquivo excedeu o tamanho mximo de 100 MB!");
                arquivo.close();
                return;
            }

            //////////////////////////////////////////// Carrega arquivo para o bucket /////////////////////////////////////////
            HttpClient client = new HttpClient();
            client.getParams().setParameter("http.useragent", "Test Client");

            BufferedReader br = null;
            String apikey = "AIzaSyAuKiAdUluAz4IEaOUoXldA8XuwEbty5V8";

            File input = new File(dir_arq.getText() + "/" + nom_arq.getText());

            PostMethod method = new PostMethod("https://www.googleapis.com/upload/storage/v1/b/" + bac.getNome()
                    + "/o?uploadType=media&name=" + nom_arq.getText());
            method.addParameter("uploadType", "media");
            method.addParameter("name", nom_arq.getText());
            method.setRequestEntity(new InputStreamRequestEntity(new FileInputStream(input), input.length()));
            //       method.setRequestHeader("Content-type", "image/png; charset=ISO-8859-1");
            method.setRequestHeader("Content-type", "application/octet-stream");

            //       try{
            int returnCode = client.executeMethod(method);

            if (returnCode == HttpStatus.SC_NOT_IMPLEMENTED) {
                System.err.println("The Post method is not implemented by this URI");
                method.getResponseBodyAsString();
            } else {
                br = new BufferedReader(new InputStreamReader(method.getResponseBodyAsStream()));
                String readLine;
                while (((readLine = br.readLine()) != null)) {
                    System.err.println(readLine);
                }
                br.close();
            }

        } catch (Exception e) {
            System.err.println(e);

        }
        JOptionPane.showMessageDialog(null, "Arquivo carregado com sucesso!");
    }
}

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

public String httpPost(String request, String[] paramNames, String[] paramVals) {

    Protocol.registerProtocol("https",
            new Protocol("https", new HttpRestUtils().new AcceptAllTrustFactory(), 443));

    PostMethod post = new PostMethod(request);

    post.setRequestHeader("Accept", "application/json");

    try {//from   w w  w . j a  va  2 s .co  m
        for (int i = 0; i < paramNames.length; i++) {
            if (paramNames[i] != null && paramVals[i] != null) {
                post.addParameter(paramNames[i], paramVals[i]);
            }
        }

        HttpClient client = new HttpClient();
        int status = client.executeMethod(post);
        if (status != 200) {
            System.err.println("Status was not 200.");
        }

        InputStream responseStream = post.getResponseBodyAsStream();

        if (responseStream != null) {
            return IOUtils.toString(responseStream);
        }

    } catch (FileNotFoundException e1) {
        e1.printStackTrace();
    } catch (HttpException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    return "There was an error and the POST request was not finished.";
}

From source file:com.jaspersoft.jasperserver.war.common.HeartbeatBean.java

public void contributeToHttpCall(PostMethod post) {
    post.addParameter("callCount", String.valueOf(callCount));
    post.addParameter("osName", osName);
    post.addParameter("osVersion", osVersion);
    post.addParameter("javaVendor", javaVendor);
    post.addParameter("javaVersion", javaVersion);
    post.addParameter("serverInfo", serverInfo);
    post.addParameter("productName", productName);
    post.addParameter("productVersion", productVersion);
    post.addParameter("dbName", dbName);
    post.addParameter("dbVersion", dbVersion);
    post.addParameter("serverLocale", Locale.getDefault().toString());

    try {//from   w ww  .  j a  v  a 2  s.c  o m
        post.addParameter("tenants", String.valueOf(tenantService.getNumberOfTenants(null)));
    } catch (Exception e) {
        if (log.isDebugEnabled())
            log.debug("Getting number of tenants failed.", e);
    }

    try {
        UserLocale[] userLocales = localesList.getUserLocales(Locale.getDefault());
        if (userLocales != null && userLocales.length > 0) {
            StringBuffer sbuffer = new StringBuffer();
            for (int i = 0; i < userLocales.length; i++) {
                sbuffer.append(", " + userLocales[i].getCode());
            }
            post.addParameter("userLocales", sbuffer.substring(2));
        }
    } catch (Exception e) {
        if (log.isDebugEnabled())
            log.debug("Getting user locales failed.", e);
    }

    clientInfoCache.contributeToHttpCall(post);

    databaseInfoCache.contributeToHttpCall(post);
    customDSInfoCache.contributeToHttpCall(post);

    awsEc2Contributor.contributeToHttpCall(post);

    if (optionalContributor != null) {
        optionalContributor.contributeToHttpCall(post);
    }
}

From source file:JiraWebSession.java

private HostConfiguration login(HttpClient httpClient, IProgressMonitor monitor) throws JiraException {
    RedirectTracker tracker = new RedirectTracker();

    final String restLogin = "/rest/gadget/1.0/login"; //$NON-NLS-1$ // JIRA 4.x has additional endpoint for login that tells if CAPTCHA limit was hit
    final String loginAction = "/secure/Dashboard.jspa"; //$NON-NLS-1$;
    boolean jira4x = true;

    for (int i = 0; i <= MAX_REDIRECTS; i++) {
        AuthenticationCredentials credentials = location.getCredentials(AuthenticationType.REPOSITORY);
        if (credentials == null) {
            // TODO prompt user?
            credentials = new AuthenticationCredentials("", ""); //$NON-NLS-1$ //$NON-NLS-2$
        }/*w ww .j  ava 2  s. c  o  m*/

        String url = baseUrl + (jira4x ? restLogin : loginAction);

        PostMethod login = new PostMethod(url);
        login.setFollowRedirects(false);
        login.setRequestHeader("Content-Type", getContentType()); //$NON-NLS-1$
        login.addParameter("os_username", credentials.getUserName()); //$NON-NLS-1$
        login.addParameter("os_password", credentials.getPassword()); //$NON-NLS-1$
        login.addParameter("os_destination", "/success"); //$NON-NLS-1$ //$NON-NLS-2$

        tracker.addUrl(url);

        try {
            HostConfiguration hostConfiguration = WebUtil.createHostConfiguration(httpClient, location,
                    monitor);
            int statusCode = WebUtil.execute(httpClient, hostConfiguration, login, monitor);

            if (statusCode == HttpStatus.SC_NOT_FOUND) {
                jira4x = false;
                continue;
            }

            if (needsReauthentication(httpClient, login, monitor)) {
                continue;
            } else if (statusCode != HttpStatus.SC_MOVED_TEMPORARILY
                    && statusCode != HttpStatus.SC_MOVED_PERMANENTLY) {
                throw new JiraServiceUnavailableException("Unexpected status code during login: " + statusCode); //$NON-NLS-1$
            }

            tracker.addRedirect(url, login, statusCode);

            this.characterEncoding = login.getResponseCharSet();

            Header locationHeader = login.getResponseHeader("location"); //$NON-NLS-1$
            if (locationHeader == null) {
                throw new JiraServiceUnavailableException("Invalid redirect, missing location"); //$NON-NLS-1$
            }
            url = locationHeader.getValue();
            tracker.checkForCircle(url);
            if (!insecureRedirect && isSecure() && url.startsWith("http://")) { //$NON-NLS-1$
                tracker.log("Redirect to insecure location during login to repository: " + client.getBaseUrl()); //$NON-NLS-1$
                insecureRedirect = true;
            }
            if (url.endsWith("/success")) { //$NON-NLS-1$
                String newBaseUrl = url.substring(0, url.lastIndexOf("/success")); //$NON-NLS-1$
                if (baseUrl.equals(newBaseUrl) || !client.getLocalConfiguration().getFollowRedirects()) {
                    // success
                    addAuthenticationCookie(httpClient, login);
                    return hostConfiguration;
                } else {
                    // need to login to make sure HttpClient picks up the session cookie
                    baseUrl = newBaseUrl;
                }
            }
        } catch (IOException e) {
            throw new JiraServiceUnavailableException(e);
        } finally {
            login.releaseConnection();
        }
    }

    tracker.log(
            "Exceeded maximum number of allowed redirects during login to repository: " + client.getBaseUrl()); //$NON-NLS-1$

    throw new JiraServiceUnavailableException("Exceeded maximum number of allowed redirects during login"); //$NON-NLS-1$
}

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

@Nonnull
public <T> RestResponse<T> httpPost(@Nonnull String path, @Nonnull String[] paramNames,
        @Nonnull String[] paramVals, @Nonnull Class<T> targetClass) {

    if (isUnsafeFlag())
        Protocol.registerProtocol("https", new Protocol("https", new AcceptAllTrustFactory(), 443));

    String urlString = makePostUrl(path);
    if (urlString == null) {
        LOGGER.debug("The POST url could not be generated. Aborting request.");
        return ResponseParser
                .getErrorResponse("The POST url could not be generated and the request was not attempted.", 0);
    }/*from w ww.  j ava  2s .c  o  m*/

    PostMethod post = new PostMethod(urlString);

    post.setRequestHeader("Accept", "application/json");

    int responseCode = -1;
    RestResponse<T> response = null;

    try {
        for (int i = 0; i < paramNames.length; i++) {
            if (paramNames[i] != null && paramVals[i] != null) {
                post.addParameter(paramNames[i], paramVals[i]);
            }
        }

        addApiKey(post);

        HttpClient client = new HttpClient();
        responseCode = client.executeMethod(post);
        if (responseCode != 200) {
            LOGGER.warn(
                    "Request for '" + urlString + "' status was " + responseCode + ", not 200 as expected.");
        }

        if (responseCode == 302) {
            Header location = post.getResponseHeader("Location");
            printRedirectInformation(location);
        }

        response = ResponseParser.getRestResponse(post.getResponseBodyAsStream(), responseCode, targetClass);

    } catch (SSLHandshakeException sslHandshakeException) {

        importCert(sslHandshakeException);

    } catch (IOException e1) {
        LOGGER.error("Encountered IOException while trying to post to " + path, e1);
        response = ResponseParser.getErrorResponse("There was an error and the POST request was not finished.",
                responseCode);
    }

    return response;
}

From source file:edu.ucuenca.authorsrelatedness.Distance.java

public synchronized String Http2(String s, Map<String, String> mp) throws SQLException, IOException {
    String md = s + mp.toString();
    String get = Cache.getInstance().get(md);
    String resp = "";
    if (get != null) {
        resp = get;//  w w  w . j av a2 s .  c  o m
    } else {
        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());
        }

        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();
            Cache.getInstance().put(md, resp);

        }

    }

    return resp;
}

From source file:com.jaspersoft.jasperserver.war.common.HeartbeatBean.java

private synchronized void httpCall(String url, HeartbeatContributor contributor) {
    if (log.isDebugEnabled())
        log.debug("Heartbeat calling: " + url);

    HttpClient httpClient = new HttpClient();

    PostMethod post = new PostMethod(url);

    try {/*from   w  ww  .  j a va2  s  .  c o m*/
        if (heartbeatId != null) {
            post.addParameter("id", heartbeatId);
        }

        if (contributor != null) {
            contributor.contributeToHttpCall(post);
        }

        int statusCode = httpClient.executeMethod(post);
        if (statusCode == HttpStatus.SC_OK) {
            if (heartbeatId == null) {
                heartbeatId = post.getResponseBodyAsString();
                heartbeatId = heartbeatId == null ? null : heartbeatId.trim();

                localIdProperties.setProperty(PROPERTY_HEARTBEAT_ID, heartbeatId);

                saveLocalIdProperties();
            }
        } else if (
        //supported types of redirect
        statusCode == HttpStatus.SC_MOVED_PERMANENTLY || statusCode == HttpStatus.SC_MOVED_TEMPORARILY
                || statusCode == HttpStatus.SC_SEE_OTHER || statusCode == HttpStatus.SC_TEMPORARY_REDIRECT) {
            Header header = post.getResponseHeader("location");
            if (header != null) {
                if (log.isDebugEnabled())
                    log.debug("Heartbeat listener redirected.");

                httpCall(header.getValue(), contributor);
            } else {
                if (log.isDebugEnabled())
                    log.debug("Heartbeat listener redirected to unknown destination.");
            }
        } else {
            if (log.isDebugEnabled())
                log.debug("Connecting to heartbeat listener URL failed. Status code: " + statusCode);
        }
    } catch (IOException e) {
        if (log.isDebugEnabled())
            log.debug("Connecting to heartbeat listener URL failed.", e);
    } finally {
        // Release current connection to the connection pool once you are done
        post.releaseConnection();

        clearCache();
    }
}

From source file:edu.ucuenca.authorsdisambiguation.nwd.NWD.java

public synchronized String Http2(String s, Map<String, String> mp, String prefix)
        throws SQLException, IOException {
    String md = s + mp.toString();
    String get = Cache.getInstance().get(prefix + md);
    String resp = "";
    if (get != null) {
        resp = get;//from  ww  w .j av  a2 s  .com
    } else {
        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());
        }

        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();
            Cache.getInstance().put(prefix + md, resp);

        }

    }

    return resp;
}

From source file:com.tacitknowledge.maven.plugin.crx.CRXPackageInstallerPlugin.java

private void checkin(final Cookie[] cookies, String path, HttpClient client)
        throws HttpException, IOException, MojoExecutionException {
    getLog().info("Checking in " + path);
    getLog().info(crxPath + "/browser/content.jsp?Path=" + path + "&action_ops=checkin");

    PostMethod checkinCall = new PostMethod(crxPath + "/browser/content.jsp");
    checkinCall.setFollowRedirects(false);

    checkinCall.addParameter("Path", path);
    checkinCall.addParameter("action_ops", "checkin");

    int status = client.executeMethod(checkinCall);

    if (status == HttpStatus.SC_OK) {
        getLog().info("Successfully checked in.\r\n");
    } else {/*from   ww w  . j a va2s.c o m*/
        logResponseDetails(checkinCall);
        throw new MojoExecutionException(
                "Removing node " + path + " failed, response=" + HttpStatus.getStatusText(status));
    }
}

From source file:com.tacitknowledge.maven.plugin.crx.CRXPackageInstallerPlugin.java

private void checkout(final Cookie[] cookies, String path, HttpClient client)
        throws HttpException, IOException, MojoExecutionException {
    getLog().info("Checking out " + path);
    getLog().info(crxPath + "/browser/content.jsp?Path=" + path + "&action_ops=checkout");

    PostMethod checkoutCall = new PostMethod(crxPath + "/browser/content.jsp");
    checkoutCall.setFollowRedirects(false);

    checkoutCall.addParameter("Path", path);
    checkoutCall.addParameter("action_ops", "checkout");

    int status = client.executeMethod(checkoutCall);

    if (status == HttpStatus.SC_OK) {
        getLog().info("Successfully checked out.\r\n");
    } else {/*from w  w  w.ja  va 2s.  co m*/
        logResponseDetails(checkoutCall);
        throw new MojoExecutionException(
                "Removing node " + path + " failed, response=" + HttpStatus.getStatusText(status));
    }
}