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.appenginefan.toolkit.common.HttpClientEnvironment.java

@Override
public String fetch(String data) {
    LOG.fine("sending " + data);
    PostMethod method = new PostMethod(url);
    method.setRequestBody(data);/*from   ww  w  .ja v  a  2  s  .c  o  m*/
    try {
        int returnCode = client.executeMethod(method);
        if (returnCode == HttpStatus.SC_OK) {
            String response = method.getResponseBodyAsString();
            LOG.fine("receiving " + response);
            return response;
        } else {
            LOG.log(Level.WARNING, "Communication failed, status code " + returnCode);
        }
    } catch (HttpException e) {
        LOG.log(Level.WARNING, "Communication failed ", e);
    } catch (IOException e) {
        LOG.log(Level.WARNING, "Communication failed ", e);
    } finally {
        method.releaseConnection();
    }
    return null;
}

From source file:com.cloud.cluster.ClusterServiceServletImpl.java

@Override
public String execute(ClusterServicePdu pdu) throws RemoteException {

    HttpClient client = getHttpClient();
    PostMethod method = new PostMethod(_serviceUrl);

    method.addParameter("method", Integer.toString(RemoteMethodConstants.METHOD_DELIVER_PDU));
    method.addParameter("sourcePeer", pdu.getSourcePeer());
    method.addParameter("destPeer", pdu.getDestPeer());
    method.addParameter("pduSeq", Long.toString(pdu.getSequenceId()));
    method.addParameter("pduAckSeq", Long.toString(pdu.getAckSequenceId()));
    method.addParameter("agentId", Long.toString(pdu.getAgentId()));
    method.addParameter("gsonPackage", pdu.getJsonPackage());
    method.addParameter("stopOnError", pdu.isStopOnError() ? "1" : "0");
    method.addParameter("pduType", Integer.toString(pdu.getPduType()));

    return executePostMethod(client, method);
}

From source file:fedora.server.security.servletfilters.pubcookie.ConnectPubcookie.java

private static final HttpMethodBase setup(HttpClient client, URL url, Map requestParameters,
        Cookie[] requestCookies) {//from  ww  w  .j  a  v a  2s. co  m
    LogFactory.getLog(ConnectPubcookie.class).debug(ConnectPubcookie.class.getName() + ".setup()");
    HttpMethodBase method = null;
    if (requestParameters == null) {
        LogFactory.getLog(ConnectPubcookie.class)
                .debug(ConnectPubcookie.class.getName() + ".setup()" + " requestParameters == null");
        method = new GetMethod(url.toExternalForm());
        //GetMethod is superclass to ExpectContinueMethod, so we don't require method.setUseExpectHeader(false);
        LogFactory.getLog(ConnectPubcookie.class)
                .debug(ConnectPubcookie.class.getName() + ".setup()" + " after getting method");
    } else {
        LogFactory.getLog(ConnectPubcookie.class)
                .debug(ConnectPubcookie.class.getName() + ".setup()" + " requestParameters != null");
        method = new PostMethod(url.toExternalForm()); // "http://localhost:8080/"
        LogFactory.getLog(ConnectPubcookie.class)
                .debug(ConnectPubcookie.class.getName() + ".setup()" + " after getting method");

        //XXX method.getParams().setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE, false); //new way
        //XXX method.getParams().setIntParameter(HttpMethodParams.SO_TIMEOUT, 10000);            
        //XXX method.getParams().setVersion(HttpVersion.HTTP_0_9); //or HttpVersion.HTTP_1_0 HttpVersion.HTTP_1_1

        LogFactory.getLog(ConnectPubcookie.class)
                .debug(ConnectPubcookie.class.getName() + ".setup()" + " after setting USE_EXPECT_CONTINUE");

        //PostMethod is subclass of ExpectContinueMethod, so we require here:            
        //((PostMethod)method).setUseExpectHeader(false);
        //client.setTimeout(30000); // increased from 10000 as temp fix; 2005-03-17 wdn5e
        //HttpClientParams httpClientParams = new HttpClientParams();
        //httpClientParams.setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE, true); //old way
        //httpClientParams.setIntParameter(HttpMethodParams.SO_TIMEOUT, 30000);

        LogFactory.getLog(ConnectPubcookie.class).debug(ConnectPubcookie.class.getName() + ".setup()" + " A");

        Part[] parts = new Part[requestParameters.size()];
        Iterator iterator = requestParameters.keySet().iterator();
        for (int i = 0; iterator.hasNext(); i++) {
            String fieldName = (String) iterator.next();
            String fieldValue = (String) requestParameters.get(fieldName);
            StringPart stringPart = new StringPart(fieldName, fieldValue);
            parts[i] = stringPart;
            LogFactory.getLog(ConnectPubcookie.class).debug(ConnectPubcookie.class.getName() + ".setup()"
                    + " part[" + i + "]==" + fieldName + "=" + fieldValue);

            ((PostMethod) method).addParameter(fieldName, fieldValue); //old way
        }

        LogFactory.getLog(ConnectPubcookie.class).debug(ConnectPubcookie.class.getName() + ".setup()" + " B");

        //XXX MultipartRequestEntity multipartRequestEntity = new MultipartRequestEntity(parts, method.getParams());
        // ((PostMethod)method).setRequestEntity(multipartRequestEntity); //new way            
    }
    //method.getParams().setCookiePolicy(CookiePolicy.RFC_2109);
    HttpState state = client.getState();
    for (Cookie cookie : requestCookies) {
        state.addCookie(cookie);
    }
    //method.setFollowRedirects(true); this is disallowed at runtime, so redirect won't be honored

    LogFactory.getLog(ConnectPubcookie.class).debug(ConnectPubcookie.class.getName() + ".setup()" + " C");
    LogFactory.getLog(ConnectPubcookie.class)
            .debug(ConnectPubcookie.class.getName() + ".setup()" + " method==" + method);
    LogFactory.getLog(ConnectPubcookie.class)
            .debug(ConnectPubcookie.class.getName() + ".setup()" + " method==" + method.toString());
    return method;
}

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);/*from  w w  w .j  a  v  a 2 s.co  m*/

    // 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 {
        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();
    }
}

From source file:com.groupon.jenkins.dotci.notifiers.WebhookNotifier.java

@Override
protected boolean notify(DynamicBuild build, BuildListener listener) {
    Map<String, ?> options = (Map<String, ?>) getOptions();
    HttpClient client = getHttpClient();
    String requestUrl = (String) options.get("url");
    PostMethod post = new PostMethod(requestUrl);

    Map<String, String> payload = (Map<String, String>) options.get("payload");
    ObjectMapper objectMapper = new ObjectMapper();

    try {//from   ww  w  .java  2 s. co m
        String payloadJson = objectMapper.writeValueAsString(payload);
        StringRequestEntity requestEntity = new StringRequestEntity(payloadJson, "application/json", "UTF-8");
        post.setRequestEntity(requestEntity);
        int statusCode = client.executeMethod(post);
        listener.getLogger().println(
                "Posted Paylod " + payloadJson + " to " + requestUrl + " with response code " + statusCode);
    } catch (Exception e) {
        listener.getLogger().print("Failed to make a POST to webhook. Check Jenkins logs for exceptions.");
        LOGGER.log(Level.WARNING, "Error posting to webhook", e);
        return false;
    } finally {
        post.releaseConnection();
    }
    return false;
}

From source file:com.groupon.jenkins.dotci.notifiers.HipchatNotifier.java

@Override
public boolean notify(DynamicBuild build, BuildListener listener) {
    List rooms = getRooms();//from   w w  w. j  av a 2  s  .c o  m
    listener.getLogger().println("sending hipchat notifications");
    for (Object roomId : rooms) {
        HttpClient client = getHttpClient();
        String url = "https://api.hipchat.com/v1/rooms/message?auth_token=" + getHipchatConfig().getToken();
        PostMethod post = new PostMethod(url);
        String urlMsg = " (<a href='" + build.getFullUrl() + "'>Open</a>)";

        try {
            post.addParameter("from", "CI");
            post.addParameter("room_id", roomId.toString());
            post.addParameter("message", getNotificationMessage(build, listener) + " " + urlMsg);
            post.addParameter("color", getColor(build, listener));
            post.addParameter("notify", shouldNotify(getColor(build, listener)));
            post.getParams().setContentCharset("UTF-8");
            client.executeMethod(post);
        } catch (Exception e) {
            listener.getLogger()
                    .print("Failed to send hipchat notifications. Check Jenkins logs for exceptions.");
            LOGGER.log(Level.WARNING, "Error posting to HipChat", e);
        } finally {
            post.releaseConnection();
        }
    }
    return true;
}

From source file:com.predic8.membrane.core.interceptor.rewrite.RewriteInterceptorIntegrationTest.java

private PostMethod getPostMethod() {
    PostMethod post = new PostMethod("http://localhost:3006/blz-service?wsdl");
    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;/*w w w. ja va  2s  .  co  m*/
}

From source file:de.michaeltamm.W3cMarkupValidator.java

/**
 * Validates the given <code>html</code>.
 *
 * @param html a complete HTML document/*from  w w  w.j  ava 2s  .  co  m*/
 */
public W3cMarkupValidationResult validate(String html) {
    if (_httpClient == null) {
        final MultiThreadedHttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager();
        _httpClient = new HttpClient(connectionManager);
    }
    final PostMethod postMethod = new PostMethod(_checkUrl);
    final Part[] data = {
            // The HTML to validate ...
            new StringPart("fragment", html, "UTF-8"), new StringPart("prefill", "0", "UTF-8"),
            new StringPart("doctype", "Inline", "UTF-8"), new StringPart("prefill_doctype", "html401", "UTF-8"),
            // List Messages Sequentially | Group Error Messages by Type ...
            new StringPart("group", "0", "UTF-8"),
            // Show source ...
            new StringPart("ss", "1", "UTF-8"),
            // Verbose Output ...
            new StringPart("verbose", "1", "UTF-8"), };
    postMethod.setRequestEntity(new MultipartRequestEntity(data, postMethod.getParams()));
    try {
        final int status = _httpClient.executeMethod(postMethod);
        if (status != 200) {
            throw new RuntimeException(_checkUrl + " responded with " + status);
        }
        final String pathPrefix = _checkUrl.substring(0, _checkUrl.lastIndexOf('/') + 1);
        final String resultPage = getResponseBody(postMethod).replace("\"./", "\"" + pathPrefix)
                .replace("src=\"images/", "src=\"" + pathPrefix + "images/")
                .replace("<script type=\"text/javascript\" src=\"loadexplanation.js\">",
                        "<script type=\"text/javascript\" src=\"" + pathPrefix + "loadexplanation.js\">");
        return new W3cMarkupValidationResult(resultPage);
    } catch (RuntimeException e) {
        throw e;
    } catch (Exception e) {
        throw new RuntimeException(e.getMessage(), e);
    } finally {
        postMethod.releaseConnection();
    }
}

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

@Test
public void testPost() throws Exception {
    HttpClient client = new HttpClient();
    PostMethod post = new PostMethod("http://localhost:4000/axis2/services/BLZService");
    InputStream stream = this.getClass().getResourceAsStream("/getBank.xml");

    InputStreamRequestEntity entity = new InputStreamRequestEntity(stream);
    post.setRequestEntity(entity);//w  w  w . j a v a2s  . c  o  m
    post.setRequestHeader(Header.CONTENT_TYPE, MimeType.TEXT_XML_UTF8);
    post.setRequestHeader(Header.SOAP_ACTION, "");

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

From source file:com.cellbots.communication.AppEngineCommChannel.java

@Override
public void listenForMessages(long waitTimeBetweenPolling, boolean returnStream) {
    stopReading = false;//w  w  w.  j a v  a  2 s  .co m
    new Thread(new Runnable() {
        @Override
        public void run() {
            Looper.prepare();
            while (!stopReading) {
                try {
                    resetConnection();
                    PostMethod post = new PostMethod(mHttpCmdUrl);
                    post.setParameter("msg", "{}");
                    int result = post.execute(mHttpState, mConnection);
                    String response = post.getResponseBodyAsString();
                    int cmdStart = response.indexOf(startCmdStr);
                    if (cmdStart != -1) {
                        String command = response.substring(cmdStart + startCmdStr.length());
                        command = command.substring(0, command.indexOf("\""));
                        Log.e("command", command);
                        mMessageListener.onMessage(new CommMessage(command, null, "text/text", null, null,
                                mChannelName, CommunicationManager.CHANNEL_GAE));
                    }
                    // Thread.sleep(200);
                } catch (MalformedURLException e) {
                    Log.e(TAG, "Error processing URL: " + e.getMessage());
                } catch (IOException e) {
                    Log.e(TAG, "Error reading command from URL: " + mHttpCmdUrl + " : " + e.getMessage());
                }
            }
        }
    }).start();
}