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.redhat.demo.CrmTest.java

/**
 * HTTP POST http://localhost:8181/cxf/crm/customerservice/customers is used to upload the contents of
 * the add_customer.json file to add a new customer to the system.
 * <p/>//  w  ww .  j a va 2  s .c o m
 * On the server side, it matches the CustomerService's addCustomer() method
 *
 * @throws Exception
 */
@Test
public void postCustomerTestJson() throws IOException {
    LOG.info("Sent HTTP POST request to add customer");
    String inputFile = this.getClass().getResource("/add_customer.json").getFile();
    File input = new File(inputFile);
    PostMethod post = new PostMethod(CUSTOMER_SERVICE_URL);
    post.addRequestHeader("Accept", "application/json");
    RequestEntity entity = new FileRequestEntity(input, "application/json; charset=ISO-8859-1");
    post.setRequestEntity(entity);
    HttpClient httpclient = new HttpClient();
    String res = "";

    try {
        int result = httpclient.executeMethod(post);
        LOG.info("Response status code: " + result);
        LOG.info("Response body: ");
        res = post.getResponseBodyAsString();
        LOG.info(res);
    } catch (IOException e) {
        LOG.error("Error connecting to {}", CUSTOMER_SERVICE_URL);
        LOG.error(
                "You should build the 'rest' quick start and deploy it to a local Fabric8 before running this test");
        LOG.error("Please read the README.md file in 'rest' quick start root");
        Assert.fail("Connection error");
    } finally {
        // Release current connection to the connection pool once you are
        // done
        post.releaseConnection();
    }
    Assert.assertTrue(res.contains("Jack"));

}

From source file:com.kodokux.github.api.GithubApiUtil.java

@NotNull
private static HttpMethod doREST(@NotNull final GithubAuthData auth, @NotNull final String uri,
        @Nullable final String requestBody, @NotNull final Collection<Header> headers,
        @NotNull final HttpVerb verb) throws IOException {
    HttpClient client = getHttpClient(auth.getBasicAuth(), auth.isUseProxy());
    HttpMethod method;//w w  w  .j  a  v a2  s . co  m
    switch (verb) {
    case POST:
        method = new PostMethod(uri);
        if (requestBody != null) {
            ((PostMethod) method)
                    .setRequestEntity(new StringRequestEntity(requestBody, "application/json", "UTF-8"));
        }
        break;
    case GET:
        method = new GetMethod(uri);
        break;
    case DELETE:
        method = new DeleteMethod(uri);
        break;
    case HEAD:
        method = new HeadMethod(uri);
        break;
    default:
        throw new IllegalStateException("Wrong HttpVerb: unknown method: " + verb.toString());
    }
    GithubAuthData.TokenAuth tokenAuth = auth.getTokenAuth();
    if (tokenAuth != null) {
        method.addRequestHeader("Authorization", "token " + tokenAuth.getToken());
    }
    for (Header header : headers) {
        method.addRequestHeader(header);
    }

    client.executeMethod(method);
    return method;
}

From source file:com.zimbra.qa.unittest.TestFileUpload.java

@Test
public void testAdminUploadWithCsrfInHeader() throws Exception {
    SoapHttpTransport transport = new SoapHttpTransport(TestUtil.getAdminSoapUrl());
    com.zimbra.soap.admin.message.AuthRequest req = new com.zimbra.soap.admin.message.AuthRequest(
            LC.zimbra_ldap_user.value(), LC.zimbra_ldap_password.value());
    req.setCsrfSupported(true);//from w  ww  .  j a v a 2 s .  c  om
    Element response = transport.invoke(JaxbUtil.jaxbToElement(req, SoapProtocol.SoapJS.getFactory()));
    com.zimbra.soap.admin.message.AuthResponse authResp = JaxbUtil.elementToJaxb(response);
    String authToken = authResp.getAuthToken();
    String csrfToken = authResp.getCsrfToken();
    int port = 7071;
    try {
        port = Provisioning.getInstance().getLocalServer().getIntAttr(Provisioning.A_zimbraAdminPort, 0);
    } catch (ServiceException e) {
        ZimbraLog.test.error("Unable to get admin SOAP port", e);
    }
    String Url = "https://localhost:" + port + ADMIN_UPLOAD_URL;
    PostMethod post = new PostMethod(Url);
    FilePart part = new FilePart(FILE_NAME, new ByteArrayPartSource(FILE_NAME, "some file content".getBytes()));
    String contentType = "application/x-msdownload";
    part.setContentType(contentType);
    HttpClient client = ZimbraHttpConnectionManager.getInternalHttpConnMgr().newHttpClient();
    HttpState state = new HttpState();
    state.addCookie(new org.apache.commons.httpclient.Cookie("localhost",
            ZimbraCookie.authTokenCookieName(true), authToken, "/", null, false));
    client.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
    client.setState(state);
    post.setRequestEntity(new MultipartRequestEntity(new Part[] { part }, post.getParams()));
    post.addRequestHeader(Constants.CSRF_TOKEN, csrfToken);
    int statusCode = HttpClientUtil.executeMethod(client, post);
    assertEquals("This request should succeed. Getting status code " + statusCode, HttpStatus.SC_OK,
            statusCode);
    String resp = post.getResponseBodyAsString();
    assertNotNull("Response should not be empty", resp);
    assertTrue("Incorrect HTML response", resp.contains(RESP_STR));
}

From source file:com.liferay.events.global.mobile.service.impl.MessageServiceImpl.java

@AccessControlled(guestAccessEnabled = true)
@Override/*ww  w .  jav a 2 s  . c  o m*/
public Message sendMessage(final String eventId, final long contactId, final long targetContactId,
        final String message, String signature) throws Exception {
    Map<String, String> args = new HashMap<String, String>() {
        {
            put("eventId", StringUtil.valueOf(eventId));
            put("contactId", StringUtil.valueOf(contactId));
            put("targetContactId", StringUtil.valueOf(targetContactId));
            put("message", StringUtil.valueOf(message));
        }
    };

    if (!Utils.isValidSignature(args, signature)) {
        throw new InvalidSignatureException("invalid signature");
    }

    if (!MatchLocalServiceUtil.matches(eventId, contactId, targetContactId)) {
        throw new UnmatchedException("Sender has not been matched with recipient");
    }

    EventContact sender = EventContactLocalServiceUtil.getEventContact(contactId);
    EventContact targetContact = EventContactLocalServiceUtil.getEventContact(targetContactId);

    final String groupName = GroupConstants.GUEST;
    final long companyId = PortalUtil.getDefaultCompanyId();
    final long guestGroupId = GroupLocalServiceUtil.getGroup(companyId, groupName).getGroupId();

    Message result = MessageLocalServiceUtil.addMessage(getUserId(), guestGroupId, new ServiceContext(),
            eventId, contactId, targetContactId, Utils.removeUnicode(message));

    JSONObject payloadObj = JSONFactoryUtil.createJSONObject();
    payloadObj.put("eventId", eventId);
    payloadObj.put("screen", "");
    payloadObj.put("body", Utils.removeUnicode(message));
    payloadObj.put("sound", "default");
    payloadObj.put("title", sender.getFullName());
    payloadObj.put("smallIcon", "ic_stat_lrlogo.png");
    payloadObj.put("ticker", message);
    payloadObj.put("badge", 1);
    payloadObj.put("vibrate", true);
    payloadObj.put("screen", "connectChat");
    payloadObj.put("screenDetail", String.valueOf(contactId));

    try {

        Map<String, String> postArgs = new HashMap<String, String>();
        final PostMethod postMethod = new PostMethod(
                "http://localhost:8080/api/jsonws/push-notifications-portlet.pushnotificationsdevice/send-push-notification");

        postArgs.put("channel", eventId);
        postArgs.put("emailAddress", targetContact.getEmailAddress());
        postArgs.put("payload", payloadObj.toString());
        String sig = Utils.generateSig(postArgs);

        postMethod.addParameter("channel", eventId);
        postMethod.addParameter("emailAddress", targetContact.getEmailAddress());
        postMethod.addParameter("payload", payloadObj.toString());
        postMethod.addParameter("signature", sig);
        final HttpClient httpClient = new HttpClient();
        httpClient.executeMethod(postMethod);

    } catch (Exception ex) {
        ex.printStackTrace();
    }

    return result;
}

From source file:net.jadler.AbstractJadlerStubbingIntegrationTest.java

@Test
public void havingBody() throws Exception {
    onRequest().havingBodyEqualTo("postbody").havingBody(notNullValue()).havingBody(not(isEmptyOrNullString()))
            .respond().withStatus(201);/*from   w  w  w  .  j av  a  2s .  c o  m*/

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

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

    method.releaseConnection();
}

From source file:com.yahoo.flowetl.services.http.BaseHttpGenerator.java

/**
 * Translates a http param object into a post method.
 * /*from   w w  w  . j a va  2s . co  m*/
 * @return the post method
 */
@SuppressWarnings("deprecation")
protected PostMethod getPostMethod(HttpParams in) {
    PostMethod meth = new PostMethod(String.valueOf(in.uri));
    if (in instanceof PostHttpParams) {
        PostHttpParams pin = (PostHttpParams) in;
        if (pin.additionalData instanceof Map<?, ?>) {
            Map<?, ?> bodyParams = (Map<?, ?>) pin.additionalData;
            NameValuePair[] pieces = new NameValuePair[bodyParams.size()];
            int i = 0;
            for (Entry<?, ?> kv : bodyParams.entrySet()) {
                pieces[i] = new NameValuePair(String.valueOf(kv.getKey()), String.valueOf(kv.getValue()));
                i++;
            }
            meth.setRequestBody(pieces);
        } else if (pin.additionalData instanceof String) {
            meth.setRequestBody((String) pin.additionalData);
        } else if (pin.additionalData != null) {
            meth.setRequestBody(String.valueOf(pin.additionalData));
        }
    }
    return meth;
}

From source file:edu.wustl.bulkoperator.client.BulkOperationServiceImpl.java

/**
 * This method will be called to get Job details.
 * @param jobId jobId/*from  w  ww  . j a v  a2  s.  com*/
 * @return Job Message
 * @throws BulkOperationException BulkOperationException
 */
public JobMessage getJobDetails(Long jobId) throws BulkOperationException {
    JobMessage jobMessage = null;
    if (!isLoggedIn) {
        jobMessage = new JobMessage();
        jobMessage.setOperationSuccessfull(false);
        jobMessage.addMessage(ApplicationProperties.getValue("bulk.operation.client.login.error"));
        return jobMessage;
    }

    PostMethod postMethod = new PostMethod(url + "/BulkHandler.do");
    try {
        postMethod.addParameter("jobId", jobId.toString());
        postMethod.addParameter("fromAction", "jobDetails");
        client.executeMethod(postMethod);
        InputStream inputStream = (InputStream) postMethod.getResponseBodyAsStream();
        ObjectInputStream ois = new ObjectInputStream(inputStream);
        Object object = ois.readObject();
        jobMessage = (JobMessage) object;
    } catch (IOException e) {
        List<String> listOfArguments = new ArrayList<String>();
        listOfArguments.add("Template file");
        listOfArguments.add("CSV file");
        jobMessage = new JobMessage();
        jobMessage.setOperationSuccessfull(false);
        jobMessage.addMessage(ApplicationProperties.getValue("bulk.operation.file.not.found", listOfArguments));
    } catch (ClassNotFoundException e) {
        jobMessage = new JobMessage();
        jobMessage.setOperationSuccessfull(false);
        jobMessage.addMessage(ApplicationProperties.getValue("clz.not.found.error"));
    } finally {
        postMethod.releaseConnection();
    }
    return jobMessage;
}

From source file:com.uber.jenkins.phabricator.uberalls.UberallsClient.java

public boolean recordCoverage(String sha, CodeCoverageMetrics codeCoverageMetrics) {
    if (codeCoverageMetrics != null && codeCoverageMetrics.isValid()) {
        JSONObject params = new JSONObject();
        params.put("sha", sha);
        params.put("branch", branch);
        params.put("repository", repository);
        params.put(PACKAGE_COVERAGE_KEY, codeCoverageMetrics.getPackageCoveragePercent());
        params.put(FILES_COVERAGE_KEY, codeCoverageMetrics.getFilesCoveragePercent());
        params.put(CLASSES_COVERAGE_KEY, codeCoverageMetrics.getClassesCoveragePercent());
        params.put(METHOD_COVERAGE_KEY, codeCoverageMetrics.getMethodCoveragePercent());
        params.put(LINE_COVERAGE_KEY, codeCoverageMetrics.getLineCoveragePercent());
        params.put(CONDITIONAL_COVERAGE_KEY, codeCoverageMetrics.getConditionalCoveragePercent());

        try {/*from   ww  w .ja  va 2s  .com*/
            HttpClient client = getClient();
            PostMethod request = new PostMethod(getBuilder().build().toString());
            request.addRequestHeader("Content-Type", "application/json");
            StringRequestEntity requestEntity = new StringRequestEntity(params.toString(),
                    ContentType.APPLICATION_JSON.toString(), "UTF-8");
            request.setRequestEntity(requestEntity);
            int statusCode = client.executeMethod(request);

            if (statusCode != HttpStatus.SC_OK) {
                logger.info(TAG, "Call failed: " + request.getStatusLine());
                return false;
            }
            return true;
        } catch (URISyntaxException e) {
            e.printStackTrace();
        } catch (HttpResponseException e) {
            // e.g. 404, pass
            logger.info(TAG, "HTTP Response error recording metrics: " + e);
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    return false;
}

From source file:com.autentia.mvn.plugin.changes.HttpRequest.java

/**
 * Send a GET method request to the given link using the configured HttpClient, possibly following redirects, and returns
 * the response as String./*from ww w . j  a  va  2s .com*/
 * 
 * @param cl the HttpClient
 * @param link the URL
 * @throws HttpStatusException
 * @throws IOException
 */
public byte[] sendPostRequest(final HttpClient cl, final String link, final String parameters)
        throws HttpStatusException, IOException {
    try {
        final PostMethod pm = new PostMethod(link);

        if (parameters != null) {
            final String[] params = parameters.split("&");
            for (final String param : params) {
                final String[] pair = param.split("=");
                if (pair.length == 2) {
                    pm.addParameter(pair[0], pair[1]);
                }
            }
        }

        this.getLog().info("Downloading from Bugzilla at: " + link);

        cl.executeMethod(pm);

        final StatusLine sl = pm.getStatusLine();

        if (sl == null) {
            this.getLog().error("Unknown error validating link: " + link);

            throw new HttpStatusException("UNKNOWN STATUS");
        }

        // if we get a redirect, throws exception
        if (pm.getStatusCode() == HttpStatus.SC_MOVED_TEMPORARILY) {
            this.getLog().debug("Attempt to redirect ");
            throw new HttpStatusException("Attempt to redirect");
        }

        if (pm.getStatusCode() == HttpStatus.SC_OK) {
            final InputStream is = pm.getResponseBodyAsStream();
            final ByteArrayOutputStream baos = new ByteArrayOutputStream();
            final byte[] buff = new byte[256];
            int readed = is.read(buff);
            while (readed != -1) {
                baos.write(buff, 0, readed);
                readed = is.read(buff);
            }

            this.getLog().debug("Downloading from Bugzilla was successful");
            return baos.toByteArray();
        } else {
            this.getLog().warn("Downloading from Bugzilla failed. Received: [" + pm.getStatusCode() + "]");
            throw new HttpStatusException("WRONG STATUS");
        }
    } catch (final HttpException e) {
        if (this.getLog().isDebugEnabled()) {
            this.getLog().error("Error downloading issues from Bugzilla:", e);
        } else {
            this.getLog().error("Error downloading issues from Bugzilla url: " + e.getLocalizedMessage());

        }
        throw e;
    } catch (final IOException e) {
        if (this.getLog().isDebugEnabled()) {
            this.getLog().error("Error downloading issues from Bugzilla:", e);
        } else {
            this.getLog().error("Error downloading issues from Bugzilla. Cause is " + e.getLocalizedMessage());
        }
        throw e;
    }
}

From source file:com.cloud.network.nicira.NiciraNvpApi.java

/**
 * Logs into the Nicira API. The cookie is stored in the <code>_authcookie<code> variable.
 * <p>//w  w w.  j a v a2s. c  o  m
 * The method returns false if the login failed or the connection could not be made.
 * 
 */
private void login() throws NiciraNvpApiException {
    String url;

    try {
        url = new URL(_protocol, _host, "/ws.v1/login").toString();
    } catch (MalformedURLException e) {
        s_logger.error("Unable to build Nicira API URL", e);
        throw new NiciraNvpApiException("Unable to build Nicira API URL", e);
    }

    PostMethod pm = new PostMethod(url);
    pm.addParameter("username", _adminuser);
    pm.addParameter("password", _adminpass);

    try {
        _client.executeMethod(pm);
    } catch (HttpException e) {
        throw new NiciraNvpApiException("Nicira NVP API login failed ", e);
    } catch (IOException e) {
        throw new NiciraNvpApiException("Nicira NVP API login failed ", e);
    } finally {
        pm.releaseConnection();
    }

    if (pm.getStatusCode() != HttpStatus.SC_OK) {
        s_logger.error("Nicira NVP API login failed : " + pm.getStatusText());
        throw new NiciraNvpApiException("Nicira NVP API login failed " + pm.getStatusText());
    }

    // Success; the cookie required for login is kept in _client
}