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:org.eclipse.mylyn.github.internal.GitHubService.java

/**
 * Edit an existing issue using the GitHub Issues API.
 * //from www .  jav a 2 s .  c o m
 * @param user
 *            - The user the repository is owned by
 * @param repo
 *            - The git repository where the issue tracker is hosted
 * @param issue
 *            - The GitHub issue object to create on the issue tracker.
 * 
 * @return the issue with changes
 * 
 * @throws GitHubServiceException
 * 
 *             API Doc: issues/edit/:user/:repo/:number API POST Variables:
 *             login, api-token, title, body
 */
public GitHubIssue editIssue(final String user, final String repo, final GitHubIssue issue,
        final GitHubCredentials credentials) throws GitHubServiceException {
    PostMethod method = null;
    try {

        // Create the HTTP POST method
        method = new PostMethod(gitURLBase + gitIssueRoot + EDIT + user + "/" + repo + "/" + issue.getNumber());
        // Set the users login and API token
        final NameValuePair login = new NameValuePair("login", credentials.getUsername());
        final NameValuePair token = new NameValuePair("token", credentials.getApiToken());
        final NameValuePair body = new NameValuePair("body", issue.getBody());
        final NameValuePair title = new NameValuePair("title", issue.getTitle());

        method.setRequestBody(new NameValuePair[] { login, token, body, title });

        executeMethod(method);
        GitHubShowIssue showIssue = gson.fromJson(method.getResponseBodyAsString(), GitHubShowIssue.class);

        // Make sure the changes were made properly
        if (showIssue == null || showIssue.getIssue() == null) {
            if (LOG.isErrorEnabled()) {
                LOG.error("Unexpected server response: " + method.getResponseBodyAsString());
            }
            throw new GitHubServiceException("Unexpected server response");
        }

        if (LOG.isDebugEnabled()) {
            LOG.debug("Response: " + method.getResponseBodyAsString());
            LOG.debug("URL: " + method.getURI());
        }
        return showIssue.getIssue();
    } catch (final RuntimeException runTimeException) {
        throw runTimeException;
    } catch (final Exception e) {
        throw new GitHubServiceException(e);
    } finally {
        if (method != null) {
            method.releaseConnection();
        }
    }
}

From source file:org.eclipse.mylyn.github.internal.GitHubService.java

private GitHubIssue changeIssueStatus(final String user, final String repo, String githubOperation,
        final GitHubIssue issue, final GitHubCredentials credentials) throws GitHubServiceException {
    PostMethod method = null;
    try {/*from  ww w .  j a v a 2  s.  c  o  m*/

        // Create the HTTP POST method
        method = new PostMethod(
                gitURLBase + gitIssueRoot + githubOperation + user + "/" + repo + "/" + issue.getNumber());
        // Set the users login and API token
        final NameValuePair login = new NameValuePair("login", credentials.getUsername());
        final NameValuePair token = new NameValuePair("token", credentials.getApiToken());

        method.setRequestBody(new NameValuePair[] { login, token });

        executeMethod(method);
        GitHubShowIssue showIssue = gson.fromJson(method.getResponseBodyAsString(), GitHubShowIssue.class);

        // Make sure the changes were made properly
        if (showIssue == null || showIssue.getIssue() == null) {
            if (LOG.isErrorEnabled()) {
                LOG.error("Unexpected server response: " + method.getResponseBodyAsString());
            }
            throw new GitHubServiceException("Unexpected server response");
        }

        if (LOG.isDebugEnabled()) {
            LOG.debug("Response: " + method.getResponseBodyAsString());
            LOG.debug("URL: " + method.getURI());
        }
        return showIssue.getIssue();
    } catch (final RuntimeException runTimeException) {
        throw runTimeException;
    } catch (final Exception e) {
        throw new GitHubServiceException(e);
    } finally {
        if (method != null) {
            method.releaseConnection();
        }
    }
}

From source file:org.eclipse.mylyn.internal.phabricator.core.client.AbstractTracClient.java

public void authenticateAccountManagerInternal(HttpClient httpClient, HostConfiguration hostConfiguration,
        AuthenticationCredentials credentials, IProgressMonitor monitor, String formToken)
        throws IOException, PhabricatorLoginException {
    PostMethod post = new PostMethod(WebUtil.getRequestPath(repositoryUrl + LOGIN_URL));
    post.setFollowRedirects(false);//from   w  w w. j a va2s.c  o m
    NameValuePair[] data = { new NameValuePair("referer", ""), //$NON-NLS-1$ //$NON-NLS-2$
            new NameValuePair("user", credentials.getUserName()), //$NON-NLS-1$
            new NameValuePair("password", credentials.getPassword()), //$NON-NLS-1$
            new NameValuePair("__FORM_TOKEN", formToken) }; //$NON-NLS-1$

    post.setRequestBody(data);
    try {
        if (DEBUG_AUTH) {
            System.err.println(location.getUrl() + ": Attempting form-based account manager authentication"); //$NON-NLS-1$ 
        }
        int code = WebUtil.execute(httpClient, hostConfiguration, post, monitor);
        if (DEBUG_AUTH) {
            System.err.println(location.getUrl() + ": Received account manager response (" + code + ")"); //$NON-NLS-1$ //$NON-NLS-2$ 
        }
        // code should be a redirect in case of success  
        if (code == HttpURLConnection.HTTP_OK) {
            throw new PhabricatorLoginException();
        }
    } finally {
        WebUtil.releaseConnection(post, monitor);
    }
}

From source file:org.eclipse.mylyn.internal.trac.core.client.AbstractTracClient.java

public void authenticateAccountManagerInternal(HttpClient httpClient, HostConfiguration hostConfiguration,
        AuthenticationCredentials credentials, IProgressMonitor monitor, String formToken)
        throws IOException, TracLoginException {
    PostMethod post = new PostMethod(WebUtil.getRequestPath(repositoryUrl + LOGIN_URL));
    post.setFollowRedirects(false);/*www .  j a  v  a  2  s  .  co  m*/
    NameValuePair[] data = { new NameValuePair("referer", ""), //$NON-NLS-1$ //$NON-NLS-2$
            new NameValuePair("user", credentials.getUserName()), //$NON-NLS-1$
            new NameValuePair("password", credentials.getPassword()), //$NON-NLS-1$
            new NameValuePair("__FORM_TOKEN", formToken) }; //$NON-NLS-1$

    post.setRequestBody(data);
    try {
        if (DEBUG_AUTH) {
            System.err.println(location.getUrl() + ": Attempting form-based account manager authentication"); //$NON-NLS-1$ 
        }
        int code = WebUtil.execute(httpClient, hostConfiguration, post, monitor);
        if (DEBUG_AUTH) {
            System.err.println(location.getUrl() + ": Received account manager response (" + code + ")"); //$NON-NLS-1$ //$NON-NLS-2$ 
        }
        // code should be a redirect in case of success  
        if (code == HttpURLConnection.HTTP_OK) {
            throw new TracLoginException();
        }
    } finally {
        WebUtil.releaseConnection(post, monitor);
    }
}

From source file:org.eclipse.winery.highlevelrestapi.HighLevelRestApi.java

/**
 * This method implements the HTTP Post Method
 * //from   w  w w.j  ava  2s . c  o m
 * @param uri Resource URI
 * @param requestPayload Content which has to be posted into the Resource
 * @return ResponseCode of HTTP Interaction
 */
@SuppressWarnings("deprecation")
public static HttpResponseMessage Post(String uri, String requestPayload, String acceptHeaderValue) {

    PostMethod method = null;
    if (uri.contains("?")) {
        System.out.println("Found query trying to split");
        String[] split = uri.split("\\?");
        System.out.println("Raw URI part: " + split[0]);
        System.out.println("Raw Query part: " + split[1]);
        method = new PostMethod(split[0]);
        method.setQueryString(HighLevelRestApi.createNameValuePairArrayFromQuery(split[1]));
    } else {
        method = new PostMethod(uri);
        ;
    }
    method.setRequestBody(requestPayload);
    HighLevelRestApi.setAcceptHeader(method, acceptHeaderValue);
    HttpResponseMessage responseMessage = LowLevelRestApi.executeHttpMethod(method);
    HighLevelRestApi.cleanResponseBody(responseMessage);
    return responseMessage;
}

From source file:org.eclipsecon.e4rover.client.production.ProductionServer.java

public int enterPlayerQueue(String playerKey) throws IOException {
    PostMethod post = new PostMethod(IServerConstants.QUEUE_RESTLET);

    try {/*w  w w .jav a  2s.c  o  m*/
        NameValuePair[] form = new NameValuePair[1];
        form[0] = new NameValuePair(IServerConstants.HASH, playerKey);
        post.setRequestBody(form);
        int resp = httpClient.executeMethod(post);
        if (resp == HttpStatus.SC_OK) {
            return Integer.parseInt(post.getResponseHeader(IServerConstants.QUEUE_POSITION).getValue());
        } else {
            throw new RobotServerException(resp, post.getURI(), post.getResponseBodyAsString());
        }
    } finally {
        post.releaseConnection();
    }
}

From source file:org.fao.geonet.notifier.MetadataNotifierClient.java

/**
 * Uses the notifier update service to handle insertion and updates of metadata.
 *
 * @param metadata//ww w  . j  a  v  a2s .c o  m
 * @param metadataUuid
 * @throws MetadataNotifierClientException
 */
public void webUpdate(String serviceUrl, String username, String password, String metadata, String metadataUuid,
        GeonetContext gc) throws MetadataNotifierClientException {
    HttpClient client;

    Protocol.registerProtocol("https", new Protocol("https", new EasySSLProtocolSocketFactory(), 443));

    // Create a method instance.
    PostMethod method = new PostMethod(serviceUrl);

    // Provide custom retry handler is necessary
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(3, false));

    NameValuePair[] data = { new NameValuePair("action", "update"), new NameValuePair("uuid", metadataUuid),
            new NameValuePair("XMLFile", metadata) };

    method.setRequestBody(data);

    //RequestEntity requestEntity = new InputStreamRequestEntity(isoDocumentInputStream);

    //method.setRequestEntity(requestEntity);
    try {
        // Create an instance of HttpClient.
        client = new HttpClient();

        if (StringUtils.isNotBlank(username) && StringUtils.isNotBlank(password)) {
            System.out.println("webUpdate: SET USER");
            client.getState().setCredentials(AuthScope.ANY,
                    new UsernamePasswordCredentials(username, password));

            method.setDoAuthentication(true);
        }

        System.out.println("settingMan: " + (gc.getSettingManager() != null));
        if (gc.getSettingManager() != null)
            Lib.net.setupProxy(gc.getSettingManager(), client);

        // Execute the method.
        int statusCode = client.executeMethod(method);

        if (statusCode != HttpStatus.SC_OK) {
            throw new MetadataNotifierClientException("Method failed: " + method.getStatusLine());
        }

        // Read the response body.
        // byte[] responseBody = method.getResponseBody();

        // Deal with the response.
        // Use caution: ensure correct character encoding and is not binary data
        // System.out.println(new String(responseBody));

    } catch (HttpException e) {
        throw new MetadataNotifierClientException(e);
    } catch (IOException e) {
        throw new MetadataNotifierClientException(e);
    } finally {
        // Release the connection.
        method.releaseConnection();
        client = null;
    }
}

From source file:org.fao.geonet.notifier.MetadataNotifierClient.java

/**
 * Uses the notifier delete service to handle deletion of metadata.
 *
 * @param metadataUuid//from  w  w w. java2 s.  co m
 * @throws MetadataNotifierClientException
 */
public void webDelete(String serviceUrl, String username, String password, String metadataUuid,
        GeonetContext gc) throws MetadataNotifierClientException {
    HttpClient client;

    Protocol.registerProtocol("https", new Protocol("https", new EasySSLProtocolSocketFactory(), 443));

    // Create a method instance.
    PostMethod method = new PostMethod(serviceUrl);

    // Provide custom retry handler is necessary
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(3, false));

    try {
        // Create an instance of HttpClient.
        client = new HttpClient();

        if (StringUtils.isNotBlank(username) && StringUtils.isNotBlank(password)) {
            client.getState().setCredentials(AuthScope.ANY,
                    new UsernamePasswordCredentials(username, password));
            method.setDoAuthentication(true);
        }

        if (gc.getSettingManager() != null)
            Lib.net.setupProxy(gc.getSettingManager(), client);

        NameValuePair[] data = { new NameValuePair("action", "delete"), new NameValuePair("uuid", metadataUuid),
                new NameValuePair("XMLFile", "") };

        method.setRequestBody(data);

        //RequestEntity requestEntity = new StringRequestEntity(metadataUuid, null, null);

        //method.setRequestEntity(requestEntity);

        // Execute the method.
        int statusCode = client.executeMethod(method);

        if (statusCode != HttpStatus.SC_OK) {
            throw new MetadataNotifierClientException("Method failed: " + method.getStatusLine());
        }

        // Read the response body.
        // byte[] responseBody = method.getResponseBody();

        // Deal with the response.
        // Use caution: ensure correct character encoding and is not binary data
        // System.out.println(new String(responseBody));

    } catch (HttpException e) {
        throw new MetadataNotifierClientException(e);
    } catch (IOException e) {
        throw new MetadataNotifierClientException(e);
    } finally {
        // Release the connection.
        method.releaseConnection();
        client = null;
    }
}

From source file:org.fao.oaipmh.requests.Transport.java

private HttpMethodBase setupHttpMethod() {
    HttpMethodBase httpMethod;/*from  w w w.  j ava2 s . c  o  m*/

    if (method == Method.GET) {
        httpMethod = new GetMethod();
        httpMethod.setQueryString(alParams.toArray(new NameValuePair[1]));
    } else {
        PostMethod pm = new PostMethod();
        pm.setRequestBody(alParams.toArray(new NameValuePair[1]));

        httpMethod = pm;
    }

    httpMethod.setPath(address);
    httpMethod.setDoAuthentication(useAuthent());

    return httpMethod;
}

From source file:org.firstopen.singularity.util.HTTPConnector.java

public String post() throws HttpException, IOException {

    PostMethod post = new PostMethod(url);
    post.setRequestBody(methodNVPairs);

    post.setFollowRedirects(true);/*  w ww . ja v a  2  s .  co  m*/

    return this.post(post);
}