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.intellij.internal.statistic.connect.StatisticsHttpClientSender.java

@Override
public void send(@NotNull String url, @NotNull String content) throws StatServiceException {
    PostMethod post = null;

    try {/*from  w w w . j  a v a 2  s  .c  o m*/
        //HttpConfigurable.getInstance().prepareURL(url);

        HttpClient httpclient = new HttpClient();
        post = new PostMethod(url);

        post.setRequestBody(
                new NameValuePair[] { new NameValuePair("content", content), new NameValuePair("uuid",
                        UpdateChecker.getInstallationUID(PropertiesComponent.getInstance())) });

        httpclient.executeMethod(post);

        if (post.getStatusCode() != HttpStatus.SC_OK) {
            throw new StatServiceException("Error during data sending... Code: " + post.getStatusCode());
        }

        final Header errors = post.getResponseHeader("errors");
        if (errors != null) {
            final String value = errors.getValue();

            throw new StatServiceException("Error during updating statistics "
                    + (!StringUtil.isEmptyOrSpaces(value) ? " : " + value : ""));
        }
    } catch (StatServiceException e) {
        throw e;
    } catch (Exception e) {
        throw new StatServiceException("Error during data sending...", e);
    } finally {
        if (post != null) {
            post.releaseConnection();
        }
    }
}

From source file:de.softwareforge.pgpsigner.util.HKPSender.java

public boolean uploadKey(final byte[] armoredKey) {

    PostMethod post = new PostMethod(UPLOAD_URL);

    try {/*from w  w  w  . j  av a2  s . com*/

        NameValuePair keyText = new NameValuePair("keytext", new String(armoredKey, "ISO-8859-1"));
        post.setRequestBody(new NameValuePair[] { keyText });
        post.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
                new DefaultHttpMethodRetryHandler(3, false));

        int statusCode = httpClient.executeMethod(post);

        if (statusCode != HttpStatus.SC_OK) {
            return false;
        }

        InputStream responseStream = post.getResponseBodyAsStream();
        InputStreamReader isr = null;
        BufferedReader br = null;
        StringBuffer response = new StringBuffer();

        try {
            isr = new InputStreamReader(responseStream);
            br = new BufferedReader(isr);
            String line = null;

            while ((line = br.readLine()) != null) {
                response.append(line);
            }
        } finally {
            IOUtils.closeQuietly(br);
            IOUtils.closeQuietly(isr);
            IOUtils.closeQuietly(responseStream);

        }
    } catch (RuntimeException re) {
        throw re;
    } catch (Exception e) {
        return false;
    } finally {
        post.releaseConnection();
    }
    return true;
}

From source file:br.org.acessobrasil.silvinha.autenticador.AutenticadorConector.java

public boolean autenticarLogin(Login login) {
    boolean autenticado = false;
    HttpClient client = new HttpClient();
    PostMethod method = new PostMethod(url);
    NameValuePair x1 = new NameValuePair("x1", login.getUser());
    NameValuePair x2 = new NameValuePair("x2", login.getPass());
    method.setRequestBody(new NameValuePair[] { x1, x2 });
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(3, false));
    try {//from w w  w.  j a  v a 2  s. c  om
        int statusCode = client.executeMethod(method);

        if (statusCode != HttpStatus.SC_OK) {
            log.error("Method failed: " + method.getStatusLine());
        }

        // Read the response body.
        byte[] responseBody = method.getResponseBody();
        String rb = new String(responseBody).trim();
        // Deal with the response.
        if (rb.startsWith("OK")) {
            autenticado = true;
            String[] rbLines = rb.split("\n");
            Token.setUrl(rbLines[1]);
        }
    } catch (HttpException he) {
        log.error("Fatal protocol violation: " + he.getMessage(), he);
    } catch (IOException ioe) {
        log.error("Fatal transport error: " + ioe.getMessage(), ioe);
    } finally {
        /*
         *  Release the connection.
        */
        method.releaseConnection();
    }

    return autenticado;
}

From source file:ch.ksfx.web.services.spidering.http.HttpClientHelper.java

public PostMethod executePostMethod(String url, NameValuePair[] nameValuePairs) {
    try {/*from   ww  w  . j a  v a 2 s  .c o m*/
        url = encodeURL(url);
        PostMethod postMethod = new PostMethod(url);
        postMethod.setFollowRedirects(false);
        postMethod.setRequestBody(nameValuePairs);
        postMethod = (PostMethod) executeMethod(postMethod);
        return postMethod;
    } catch (Exception e) {
        logger.severe("Error while generating POST method: " + e);
        return null;
    }
}

From source file:au.org.ala.cas.client.WebServiceAuthenticationHelper.java

/**
 * Authenticates user credentials with CAS server and obtains a Ticket Granting ticket.
 * /*ww w  .j a  v a2 s.c  o m*/
 * @param server   CAS server URI
 * @param username User name
 * @param password Password
 * @return The Ticket Granting Ticket id
 */
private String getTicketGrantingTicket(final String server, final String username, final String password) {
    final HttpClient client = new HttpClient();

    final PostMethod post = new PostMethod(server + CAS_CONTEXT);

    post.setRequestBody(new NameValuePair[] { new NameValuePair("username", username),
            new NameValuePair("password", password) });

    try {
        client.executeMethod(post);

        final String response = post.getResponseBodyAsString();

        switch (post.getStatusCode()) {
        case 201: {
            final Matcher matcher = Pattern.compile(".*action=\".*/(.*?)\".*").matcher(response);

            if (matcher.matches())
                return matcher.group(1);

            logger.warn("Successful ticket granting request, but no ticket found!");
            logger.info("Response (1k): " + getMaxString(response));
            break;
        }

        default:
            logger.warn("Invalid response code (" + post.getStatusCode() + ") from CAS server!");
            logger.info("Response (1k): " + getMaxString(response));
            break;
        }
    }

    catch (final IOException e) {
        logger.warn(e.getMessage(), e);
    }

    finally {
        post.releaseConnection();
    }

    return null;
}

From source file:au.org.ala.cas.client.WebServiceAuthenticationHelper.java

/**
 * Obtains a Service ticket for a web service invocation.
 * //www.  j  a  v  a  2 s.  c om
 * @param server CAS server URI
 * @param ticketGrantingTicket TGT id
 * @param service Web service URI
 * @return Service ticket id
 */
private String getServiceTicket(final String server, final String ticketGrantingTicket, final String service) {
    if (ticketGrantingTicket == null)
        return null;

    final HttpClient client = new HttpClient();

    final PostMethod post = new PostMethod(server + CAS_CONTEXT + ticketGrantingTicket);

    post.setRequestBody(new NameValuePair[] { new NameValuePair("service", service) });

    try {
        client.executeMethod(post);

        final String response = post.getResponseBodyAsString();

        switch (post.getStatusCode()) {
        case 200:
            return response;

        default:
            logger.warn("Invalid response code (" + post.getStatusCode() + ") from CAS server!");
            logger.info("Response (1k): " + getMaxString(response));
            break;
        }
    }

    catch (final IOException e) {
        logger.warn(e.getMessage(), e);
    }

    finally {
        post.releaseConnection();
    }

    return null;
}

From source file:com.mercatis.lighthouse3.commons.commons.HttpRequest.java

/**
 * This method performs an HTTP request against an URL.
 *
 * @param url         the URL to call//from w  w w  .  j av  a2 s. com
 * @param method      the HTTP method to execute
 * @param body        the body of a POST or PUT request, can be <code>null</code>
 * @param queryParams a Hash with the query parameter, can be <code>null</code>
 * @return the data returned by the web server
 * @throws HttpException in case a communication error occurred.
 */
@SuppressWarnings("deprecation")
public String execute(String url, HttpRequest.HttpMethod method, String body, Map<String, String> queryParams) {

    NameValuePair[] query = null;

    if (queryParams != null) {
        query = new NameValuePair[queryParams.size()];

        int counter = 0;
        for (Entry<String, String> queryParam : queryParams.entrySet()) {
            query[counter] = new NameValuePair(queryParam.getKey(), queryParam.getValue());
            counter++;
        }
    }

    org.apache.commons.httpclient.HttpMethod request = null;

    if (method == HttpMethod.GET) {
        request = new GetMethod(url);
    } else if (method == HttpMethod.POST) {
        PostMethod postRequest = new PostMethod(url);
        if (body != null) {
            postRequest.setRequestBody(body);
        }
        request = postRequest;
    } else if (method == HttpMethod.PUT) {
        PutMethod putRequest = new PutMethod(url);
        if (body != null) {
            putRequest.setRequestBody(body);
        }
        request = putRequest;
    } else if (method == HttpMethod.DELETE) {
        request = new DeleteMethod(url);
    }

    request.setRequestHeader("Content-type", "application/xml;charset=utf-8");
    if (query != null) {
        request.setQueryString(query);
    }

    int resultCode = 0;
    StringBuilder resultBodyBuilder = new StringBuilder();

    try {
        resultCode = this.httpClient.executeMethod(request);
        BufferedReader reader = new BufferedReader(
                new InputStreamReader(request.getResponseBodyAsStream(), Charset.forName("UTF-8")));
        String line = null;
        while ((line = reader.readLine()) != null) {
            resultBodyBuilder.append(line);
        }

        if (resultCode != 200) {
            throw new HttpException(resultBodyBuilder.toString(), null);
        }
    } catch (HttpException httpException) {
        throw new HttpException("HTTP request failed", httpException);
    } catch (IOException ioException) {
        throw new HttpException("HTTP request failed", ioException);
    } catch (NullPointerException npe) {
        throw new HttpException("HTTP request failed", npe);
    } finally {
        request.releaseConnection();
    }

    return resultBodyBuilder.toString();
}

From source file:com.github.maven.plugin.client.impl.GithubClientImpl.java

/**
 * Removes the given download from the repository download section.
 *
 * @param repositoryUrl The repository url.
 * @param artifactName The download name.
 *//*from  w  w w  .java  2s. c  o  m*/
private void delete(String repositoryUrl, String artifactName) {
    final Map<String, Integer> downloads = retrieveDownloadsInfos(repositoryUrl);

    if (!downloads.containsKey(artifactName)) {
        throw new GithubArtifactNotFoundException(
                "The download " + artifactName + " cannot be found in " + repositoryUrl);
    }

    final String downloadUrl = String.format("%s/%d", toRepositoryDownloadUrl(repositoryUrl),
            downloads.get(artifactName));

    PostMethod githubDelete = new PostMethod(downloadUrl);
    githubDelete.setRequestBody(new NameValuePair[] { new NameValuePair("_method", "delete"),
            new NameValuePair("login", login), new NameValuePair("token", token) });

    try {
        int response = httpClient.executeMethod(githubDelete);
        if (response != HttpStatus.SC_MOVED_TEMPORARILY) {
            throw new GithubException("Unexpected error " + HttpStatus.getStatusText(response));
        }
    } catch (IOException e) {
        throw new GithubException(e);
    }

    githubDelete.releaseConnection();
}

From source file:com.twinsoft.convertigo.engine.admin.services.mobiles.GetBuildStatus.java

@Override
protected void getServiceResult(HttpServletRequest request, Document document) throws Exception {
    String project = Keys.project.value(request);

    MobileApplication mobileApplication = getMobileApplication(project);

    if (mobileApplication == null) {
        throw new ServiceException("no such mobile application");
    } else {/*from   ww  w. jav  a2  s .  co m*/
        boolean bAdminRole = Engine.authenticatedSessionManager.hasRole(request.getSession(), Role.WEB_ADMIN);
        if (!bAdminRole && mobileApplication.getAccessibility() == Accessibility.Private) {
            throw new AuthenticationException("Authentication failure: user has not sufficient rights!");
        }
    }

    String platformName = Keys.platform.value(request);

    String mobileBuilderPlatformURL = EnginePropertiesManager
            .getProperty(PropertyName.MOBILE_BUILDER_PLATFORM_URL);

    URL url = new URL(mobileBuilderPlatformURL + "/getstatus");

    HostConfiguration hostConfiguration = new HostConfiguration();
    hostConfiguration.setHost(url.getHost());
    HttpState httpState = new HttpState();
    Engine.theApp.proxyManager.setProxy(hostConfiguration, httpState, url);

    PostMethod method = new PostMethod(url.toString());

    JSONObject jsonResult;
    try {
        HeaderName.ContentType.setRequestHeader(method, MimeType.WwwForm.value());
        method.setRequestBody(new NameValuePair[] {
                new NameValuePair("application", mobileApplication.getComputedApplicationName()),
                new NameValuePair("platformName", platformName),
                new NameValuePair("auth_token", mobileApplication.getComputedAuthenticationToken()),
                new NameValuePair("endpoint", mobileApplication.getComputedEndpoint(request)) });

        int methodStatusCode = Engine.theApp.httpClient.executeMethod(hostConfiguration, method, httpState);

        InputStream methodBodyContentInputStream = method.getResponseBodyAsStream();
        byte[] httpBytes = IOUtils.toByteArray(methodBodyContentInputStream);
        String sResult = new String(httpBytes, "UTF-8");

        if (methodStatusCode != HttpStatus.SC_OK) {
            throw new ServiceException(
                    "Unable to get building status for application '" + project + "' (final app name: '"
                            + mobileApplication.getComputedApplicationName() + "').\n" + sResult);
        }

        jsonResult = new JSONObject(sResult);
    } finally {
        method.releaseConnection();
    }

    Element statusElement = document.createElement("build");
    statusElement.setAttribute(Keys.project.name(), project);
    statusElement.setAttribute(Keys.platform.name(), platformName);

    if (jsonResult.has(platformName + "_status")) {
        statusElement.setAttribute("status", jsonResult.getString(platformName + "_status"));
    } else {
        statusElement.setAttribute("status", "none");
    }

    if (jsonResult.has(platformName + "_error")) {
        statusElement.setAttribute("error", jsonResult.getString(platformName + "_error"));
    }

    statusElement.setAttribute("version", jsonResult.has("version") ? jsonResult.getString("version") : "n/a");
    statusElement.setAttribute("phonegap_version",
            jsonResult.has("phonegap_version") ? jsonResult.getString("phonegap_version") : "n/a");

    statusElement.setAttribute("revision",
            jsonResult.has("revision") ? jsonResult.getString("revision") : "n/a");
    statusElement.setAttribute("endpoint",
            jsonResult.has("endpoint") ? jsonResult.getString("endpoint") : "n/a");

    document.getDocumentElement().appendChild(statusElement);
}

From source file:com.compomics.mslims.util.mascot.MascotWebConnector.MascotAuthenticatedConnection.java

/**
 * create a post method with parameters for logging out of the mascot server
 * @return the logout post method// ww w  .  j  av a 2 s. co  m
 * @throws java.lang.IllegalArgumentException
 */
private PostMethod logoutMethod() {

    PostMethod authpost = new PostMethod("/mascot/cgi/login.pl");
    // Prepare login parameters
    NameValuePair[] parameters = { new NameValuePair("action", "logout"),
            new NameValuePair("onerrdisplay", "nothing") };

    authpost.setRequestBody(parameters);

    return authpost;
}