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

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

Introduction

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

Prototype

public void setRequestEntity(RequestEntity paramRequestEntity) 

Source Link

Usage

From source file:com.calclab.emite.j2se.services.HttpConnector.java

private Runnable createSendAction(final String httpBase, final String xml, final ConnectorCallback callback) {
    return new Runnable() {
        public void run() {
            final String id = HttpConnectorID.getNext();
            Logger.debug("Connector [{0}] send: {1}", id, xml);
            final HttpClientParams params = new HttpClientParams();
            params.setConnectionManagerTimeout(10000);
            final HttpClient client = new HttpClient(params);
            int status = 0;
            String response = null;
            final PostMethod post = new PostMethod(httpBase);

            try {
                post.setRequestEntity(new StringRequestEntity(xml, "text/xml", "utf-8"));
                System.out.println("SENDING: " + xml);
                status = client.executeMethod(post);
                response = post.getResponseBodyAsString();
            } catch (final Exception e) {
                callback.onError(xml, e);
                e.printStackTrace();/*from  www.  j av a2s.  c  o  m*/
            } finally {
                post.releaseConnection();
            }

            receiveService.execute(createResponseAction(xml, callback, id, status, response));
        }
    };
}

From source file:com.temenos.interaction.commands.webhook.WebhookCommand.java

/**
 * @precondition url has been supplied/*from   w w w .  j  av  a 2  s.  c o m*/
 * @postcondition Result.Success if {@link InteractionContext#getResource()} is successfully POSTed to url
 */
@SuppressWarnings("unchecked")
@Override
public Result execute(InteractionContext ctx) {
    if (url != null && url.length() > 0) {
        Map<String, Object> properties = null;
        try {
            OEntity oentity = ((EntityResource<OEntity>) ctx.getResource()).getEntity();
            properties = transform(oentity);
        } catch (ClassCastException cce) {
            if (LOGGER.isWarnEnabled()) {
                LOGGER.warn("Failed to cast the OEntity.", cce);
            }
            Entity entity = ((EntityResource<Entity>) ctx.getResource()).getEntity();
            properties = transform(entity);
        }
        String formData = getFormData(properties);
        try {
            LOGGER.info("POST " + url + " [" + formData + "]");
            HttpClient client = new HttpClient();
            PostMethod postMethod = new PostMethod(url);
            postMethod.setRequestEntity(
                    new StringRequestEntity(formData, "application/x-www-form-urlencoded", "UTF-8"));
            client.executeMethod(postMethod);
            LOGGER.info("Status [" + postMethod.getStatusCode() + "]");
        } catch (Exception e) {
            LOGGER.error("Error POST " + url + " [" + formData + "]", e);
            return Result.FAILURE;
        }
    } else {
        LOGGER.warn("DISABLED - no url supplied");
    }
    return Result.SUCCESS;
}

From source file:jenkins.plugins.office365connector.HttpWorker.java

@Override
public void run() {
    int tried = 0;
    boolean success = false;
    HttpClient client = getHttpClient();
    client.getParams().setConnectionManagerTimeout(timeout);
    do {//from  ww  w .  j  a  va 2s. c  o  m
        tried++;
        RequestEntity requestEntity;
        try {
            // uncomment to log what message has been sent
            // log("Posted JSON: %s", data);
            requestEntity = new StringRequestEntity(data, "application/json", StandardCharsets.UTF_8.name());
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace(logger);
            break;
        }

        PostMethod post = new PostMethod(url);
        try {
            post.setRequestEntity(requestEntity);
            int responseCode = client.executeMethod(post);
            if (responseCode != HttpStatus.SC_OK) {
                String response = post.getResponseBodyAsString();
                log("Posting data to %s may have failed. Webhook responded with status code - %s", url,
                        responseCode);
                log("Message from webhook - %s", response);

            } else {
                success = true;
            }
        } catch (IOException e) {
            log("Failed to post data to webhook - %s", url);
            e.printStackTrace(logger);
        } finally {
            post.releaseConnection();
        }
    } while (tried < RETRIES && !success);

}

From source file:fr.unix_experience.owncloud_sms.engine.OCHttpClient.java

PostMethod pushSms(StringRequestEntity ent) {
    PostMethod post = new PostMethod(_serverURI.toString() + OCHttpClient.OC_PUSH_ROUTE);
    post.setRequestEntity(ent);
    return post;//w  w w . ja v a 2 s .  com
}

From source file:net.mojodna.searchable.solr.SolrIndexer.java

/**
 * Commit pending documents to the index.
 * @throws IOException/*w  w w .  j a  v a  2s .c  o  m*/
 */
protected void commit() throws IOException {
    final PostMethod post = new PostMethod(solrPath);
    post.setRequestEntity(new StringRequestEntity("<commit waitFlush=\"false\" waitSearcher=\"false\"/>",
            "text/xml", "UTF-8"));
    log.debug("Committing.");
    getHttpClient().executeMethod(post);
}

From source file:com.predic8.membrane.core.interceptor.balancer.LoadBalancingWithClusterManagerTest.java

private PostMethod getPostMethod(String request) {
    PostMethod post = new PostMethod("http://localhost:3017/axis2/services/BLZService");
    post.setRequestEntity(new InputStreamRequestEntity(this.getClass().getResourceAsStream(request)));
    post.setRequestHeader(Header.CONTENT_TYPE, MimeType.TEXT_XML_UTF8);
    post.setRequestHeader(Header.SOAP_ACTION, "");

    return post;/*from  ww w  . j a v a  2 s.  co m*/
}

From source file:com.funambol.json.dao.AuthenticatorDAOImpl.java

public JsonResponse login(String jsonObject) throws HttpException, IOException {

    String request = Utility.getUrl(serverUrl, LOGIN_URL);

    if (log.isTraceEnabled()) {
        log.trace("Login Request: " + request);
    }/* ww  w  . j a  va  2s  .c o m*/

    PostMethod post = new PostMethod(request);
    post.setRequestEntity(new StringRequestEntity(jsonObject));

    int statusCode = 0;
    String responseBody = null;
    try {
        statusCode = httpClient.executeMethod(post);
        responseBody = post.getResponseBodyAsString();
    } finally {
        post.releaseConnection();
    }

    if (log.isTraceEnabled()) {
        log.trace("---------> statusCode: " + statusCode + " responseBody: " + responseBody);
    }

    JsonResponse jsonServerResponse = new JsonResponse(statusCode, responseBody);
    return jsonServerResponse;
}

From source file:net.mojodna.searchable.solr.SolrIndexer.java

@Override
public void optimize() throws IndexingException {
    try {//from   w  ww .  j  ava2s. co m
        PostMethod post = new PostMethod(solrPath);
        post.setRequestEntity(new StringRequestEntity("<optimize waitFlush=\"false\" waitSearcher=\"false\"/>",
                "text/xml", "UTF-8"));
        log.debug("Optimizing.");
        getHttpClient().executeMethod(post);
    } catch (final IOException e) {
        throw new IndexingException(e);
    }
}

From source file:com.predic8.membrane.interceptor.MultipleLoadBalancersTest.java

private PostMethod getPostMethod(int port) {
    PostMethod post = new PostMethod("http://localhost:" + port + "/axis2/services/BLZService");
    post.setRequestEntity(new InputStreamRequestEntity(this.getClass().getResourceAsStream("/getBank.xml")));
    post.setRequestHeader(Header.CONTENT_TYPE, MimeType.TEXT_XML_UTF8);
    post.setRequestHeader(Header.SOAP_ACTION, "");

    return post;/*from  w w  w.  j  av  a 2s  .c o m*/
}

From source file:net.morphbank.webclient.RestfulPost.java

public void post(String strURL, String strXMLFilename) throws Exception {
    File input = new File(strXMLFilename);
    // Prepare HTTP post
    PostMethod post = new PostMethod(strURL);
    post.addRequestHeader("Accept", "text/xml");
    RequestEntity entity = new FileRequestEntity(input, "text/xml; charset=ISO-8859-1");
    post.setRequestEntity(entity);

    // Request content will be retrieved directly
    // from the input stream Part[] parts = {
    // Part[] parts = { new FilePart("uploadFile", strXMLFilename, input) };
    // RequestEntity entity = new MultipartRequestEntity(parts,
    // post.getParams());
    // RequestEntity entity = new FileRequestEntity(input,
    // "text/xml;charset=utf-8");
    // post.setRequestEntity(entity);
    // Get HTTP client
    HttpClient httpclient = new HttpClient();
    // Execute request
    try {/*from   w ww .  j a v a  2s  .  c om*/
        System.out.println("Trying post");
        int result = httpclient.executeMethod(post);
        // Display status code
        System.out.println("Response status code: " + result);
        // Display response
        System.out.println("Response body: ");
        InputStream response = post.getResponseBodyAsStream();
        // int j = response.read(); System.out.write(j);
        for (int i = response.read(); i != -1; i = response.read()) {
            System.out.write(i);
        }
        // System.out.flush();
    } finally {
        // Release current connection to the connection pool once you are
        // done
        post.releaseConnection();
    }
}