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

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

Introduction

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

Prototype

public PostMethod(String paramString) 

Source Link

Usage

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 {//  www  .  j a  va  2  s.  c  o 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.amazon.dtasdk.v2.connection.SignatureVerificationTest.java

@Test
public void roundTrip_withPath() throws Exception {
    Credential credential = new Credential("SECRETKEY", "KEYID");
    handler.setCredential(credential);/*from w w w .j a  v a 2  s  .  c  o  m*/

    Request request = new Request(serverUrl() + "/path/to/servlet", Request.Method.POST, "");
    setDefaultHeaders(request);
    request.setBody("{\"json\": \"value\"}");
    signer.sign(request, credential);

    PostMethod method = new PostMethod(request.getUrl());
    copyHeaders(request, method);
    method.setRequestBody(request.getBody());

    assertEquals(200, client.executeMethod(method));
}

From source file:net.bioclipse.opentox.api.ModelAlgorithm.java

@SuppressWarnings("serial")
public static String createModel(String algoURI, String datasetURI, List<String> featureURIs,
        String predictionFeatureURI, IProgressMonitor monitor)
        throws HttpException, IOException, InterruptedException, GeneralSecurityException {
    if (monitor == null)
        monitor = new NullProgressMonitor();
    int worked = 0;

    HttpClient client = new HttpClient();
    PostMethod method = new PostMethod(algoURI);
    HttpMethodHelper.addMethodHeaders(method, new HashMap<String, String>() {
        {//w  ww. j a va  2 s . c  o m
            put("Accept", "text/uri-list");
        }
    });
    // add the features etc to the URI
    datasetURI = datasetURI + "?" + asFeatureURIString(featureURIs) + "&max=100";
    logger.debug("create model, datasetURI: " + datasetURI);
    method.setParameter("dataset_uri", datasetURI);
    method.setParameter("prediction_feature", predictionFeatureURI);
    client.executeMethod(method);
    int status = method.getStatusCode();
    String modelURI = "";
    // FIXME: I should really start using the RDF response...
    String responseString = method.getResponseBodyAsString();
    logger.debug("Status: " + status);
    int tailing = 1;
    if (status == 200 || status == 202) {
        if (responseString.contains("/task/")) {
            // OK, we got a task... let's wait until it is done
            String task = responseString;
            logger.debug("response: " + task);
            Thread.sleep(andABit(500)); // let's be friendly, and wait 1 sec
            TaskState state = Task.getState(task);
            while (!state.isFinished() && !monitor.isCanceled()) {
                int onlineWorked = (int) state.getPercentageCompleted();
                if (onlineWorked > worked) {
                    // work done is difference between done before and online done
                    monitor.worked(onlineWorked - worked);
                    worked = onlineWorked;
                }
                // let's be friendly, and wait 2 secs and a bit and increase
                // that time after each wait
                int waitingTime = andABit(2000 * tailing);
                logger.debug("Waiting " + waitingTime + "ms.");
                waitUnlessInterrupted(waitingTime, monitor);
                state = Task.getState(task);
                if (state.isRedirected()) {
                    task = state.getResults();
                    logger.debug("Got a Task redirect. New task:" + task);
                }
                // but wait at most 20 secs and a bit
                if (tailing < 10)
                    tailing++;
            }
            if (monitor.isCanceled())
                Task.delete(task);
            // OK, it should be finished now
            modelURI = state.getResults();
        } else {
            // OK, that was quick!
            modelURI = responseString;
            logger.debug("No Task, Data set: " + modelURI);
            monitor.worked(100);
        }
    } else if (status == 401) {
        throw new GeneralSecurityException("Not authenticated");
    } else if (status == 403) {
        throw new GeneralSecurityException("Not authorized");
    } else if (status == 404) {
        logger.debug("Model not found (404): " + responseString);
        throw new UnsupportedOperationException("Service not found");
    } else {
        logger.debug("Model error (" + status + "): " + responseString);
        throw new IllegalStateException("Service error: " + status);
    }
    method.releaseConnection();
    modelURI = modelURI.replaceAll("\n", "");
    return modelURI;
}

From source file:net.jadler.JadlerStubbingIntegrationTest.java

@Test
public void havingEmptyBody() throws Exception {
    onRequest().havingBodyEqualTo("").havingBody(notNullValue()).havingBody(isEmptyString()).respond()
            .withStatus(201);/*from  ww  w. j a  v  a2 s  .c o  m*/

    final PostMethod method = new PostMethod("http://localhost:" + port());
    method.setRequestEntity(new StringRequestEntity("", null, null));

    int status = client.executeMethod(method);
    assertThat(status, is(201));
}

From source file:com.itude.mobile.mobbl.server.http.HttpDelegate.java

public HttpResponse connectPost(String url, String userAgent, ArrayList<Cookie> reqCookies,
        NameValuePair[] postData, Header[] requestHeaders, boolean followRedirects) {
    logger.debug("HttpDelegate.connectPost(): " + url);

    PostMethod post = new PostMethod(url);
    try {//from w  ww.j av  a2 s  . co  m
        prepareConnection(post, userAgent, reqCookies, requestHeaders, !url.contains("acceptxml=false"),
                followRedirects);
        if (postData != null)
            post.setRequestBody(postData);

        return executeHttpMethod(post);
    } catch (HttpException e) {
        logger.error(e.getMessage());
        logger.trace(e.getMessage(), e);
    } catch (IOException e) {
        logger.error(e.getMessage());
        logger.trace(e.getMessage(), e);
    } finally {
        post.releaseConnection();
    }

    return null;
}

From source file:com.predic8.membrane.integration.AccessControlInterceptorIntegrationTest.java

private PostMethod getBLZRequestMethod() {
    PostMethod post = new PostMethod("http://localhost:3008/axis2/services/BLZService");
    InputStream stream = this.getClass().getResourceAsStream("/getBank.xml");

    InputStreamRequestEntity entity = new InputStreamRequestEntity(stream);
    post.setRequestEntity(entity);/*from  w w w  .  j a  va  2s .  c  om*/
    post.setRequestHeader(Header.CONTENT_TYPE, MimeType.TEXT_XML_UTF8);
    post.setRequestHeader(Header.SOAP_ACTION, "\"\"");
    return post;
}

From source file:com.salas.bbservice.service.forum.ForumHandler.java

/**
 * Posts a new topic to the forum./* w w w  .  j a v a2  s .c  o  m*/
 *
 * @param aFullName full name of the author.
 * @param aEmail    optional email address of the author.
 * @param aForumId  ID of the forum to post topic to.
 * @param aSubject  subject of the post.
 * @param aMessage  message of the post.
 */
private void post(String aFullName, String aEmail, int aForumId, String aSubject, String aMessage)
        throws IOException {
    PostMethod post = new PostMethod(forumBaseURL + "/post.php?action=post&fid=" + aForumId);
    post.addParameter("form_sent", "1");
    post.addParameter("form_user", "Guest");
    post.addParameter("req_username", "[BB] " + aFullName.trim());
    post.addParameter("email", StringUtils.isEmpty(aEmail) ? "" : aEmail.trim());
    post.addParameter("req_subject", aSubject.trim());
    post.addParameter("req_message", aMessage.trim());

    HttpClient client = new HttpClient();
    int status = client.executeMethod(post);

    if (status >= 400)
        throw new IOException("Failed to publish topic.");
}

From source file:com.isencia.passerelle.model.util.RESTFacade.java

/**
 * /*from w ww.j a  v  a2s .  c om*/
 * @param fHandle
 * @return the flow handle with its newly obtained execId
 * 
 * @throws PasserelleException
 * @throws IllegalStateException e.g. when the flow is already executing
 * @throws IllegalArgumentException e.g. when the handle does not correspond to an existing flow
 * 
 */
public FlowHandle startFlowRemotely(FlowHandle fHandle)
        throws PasserelleException, IllegalStateException, IllegalArgumentException {
    String startURL = fHandle.getAuthorativeResourceLocation().toString();
    startURL += "/launch";
    String startInfo = invokeMethodForURL(new PostMethod(startURL));
    SAXBuilder parser = new SAXBuilder();
    Document doc = null;
    try {
        doc = parser.build(new StringReader(startInfo));
    } catch (Exception e) {
        throw new PasserelleException("Unable to parse response data", startInfo, e);
    }
    if (doc != null) {
        Element scheduledJobElement = doc.getRootElement().getChild("scheduledJob");
        Element execInfo = scheduledJobElement.getChild("execInfo");
        String execId = execInfo.getAttributeValue("id");
        String execHREF = execInfo.getAttributeValue("href");
        fHandle.setExecId(execId);
        try {
            fHandle.setExecResourceLocation(new URL(execHREF));
        } catch (Exception e) {
            throw new PasserelleException("Invalid URL " + execHREF + " in response ", startInfo, e);
        }
    }
    return fHandle;
}

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

public void upload(String artifactName, File file, String description, String repositoryUrl) {
    assertNotNull(artifactName, "artifactName");
    assertNotNull(file, "file");
    assertNotNull(repositoryUrl, "repositoryUrl");
    assertStartsWith(repositoryUrl, GITHUB_REPOSITORY_URL_PREFIX, "repositoryUrl");

    PostMethod githubPost = new PostMethod(toRepositoryDownloadUrl(repositoryUrl));
    githubPost.setRequestBody(new NameValuePair[] { new NameValuePair("login", login),
            new NameValuePair("token", token), new NameValuePair("file_name", artifactName),
            new NameValuePair("file_size", String.valueOf(file.length())),
            new NameValuePair("description", description == null ? "" : description) });

    try {/*from   w w  w  . j a v  a  2s .  c  o  m*/

        int response = httpClient.executeMethod(githubPost);

        if (response == HttpStatus.SC_OK) {

            ObjectMapper mapper = new ObjectMapper();
            JsonNode node = mapper.readValue(githubPost.getResponseBodyAsString(), JsonNode.class);

            PostMethod s3Post = new PostMethod(GITHUB_S3_URL);

            Part[] parts = { new StringPart("Filename", artifactName),
                    new StringPart("policy", node.path("policy").getTextValue()),
                    new StringPart("success_action_status", "201"),
                    new StringPart("key", node.path("path").getTextValue()),
                    new StringPart("AWSAccessKeyId", node.path("accesskeyid").getTextValue()),
                    new StringPart("Content-Type", node.path("mime_type").getTextValue()),
                    new StringPart("signature", node.path("signature").getTextValue()),
                    new StringPart("acl", node.path("acl").getTextValue()), new FilePart("file", file) };

            MultipartRequestEntity partEntity = new MultipartRequestEntity(parts, s3Post.getParams());
            s3Post.setRequestEntity(partEntity);

            int s3Response = httpClient.executeMethod(s3Post);
            if (s3Response != HttpStatus.SC_CREATED) {
                throw new GithubException(
                        "Cannot upload " + file.getName() + " to repository " + repositoryUrl);
            }

            s3Post.releaseConnection();
        } else if (response == HttpStatus.SC_NOT_FOUND) {
            throw new GithubRepositoryNotFoundException("Cannot found repository " + repositoryUrl);
        } else if (response == HttpStatus.SC_UNPROCESSABLE_ENTITY) {
            throw new GithubArtifactAlreadyExistException(
                    "File " + artifactName + " already exist in " + repositoryUrl + " repository");
        } else {
            throw new GithubException("Error " + HttpStatus.getStatusText(response));
        }
    } catch (IOException e) {
        throw new GithubException(e);
    }

    githubPost.releaseConnection();
}

From source file:eu.seaclouds.platform.planner.optimizerTest.service.OptimizerServiceOpenShiftTest.java

@Test(enabled = TestConstants.EnabledTestOpenShift)
public void testPresenceSolutionAnneal() {

    log.info("=== TEST for SOLUTION GENERATION of ANNEAL optimizer service STARTED ===");

    String url = BASE_URL + "optimize";

    HttpClient client = new HttpClient();
    PostMethod method = new PostMethod(url);

    method.addParameter("aam", appModel);
    method.addParameter("offers", suitableCloudOffer);
    method.addParameter("optmethod", SearchMethodName.ANNEAL.toString());

    executeAndCheck(client, method, SearchMethodName.ANNEAL.toString());

    log.info("=== TEST for SOLUTION GENERATION of ANNEAL optimizer service DEPLOYED IN OPENSHIFT FINISEHD ===");

}