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.google.apphosting.vmruntime.jetty9.VmRuntimeJettyKitchenSink2Test.java

/**
 * Test that blob upload requests are intercepted by the blob upload filter.
 *
 * @throws Exception/*  ww w  .j  a  va 2s. co  m*/
 */
public void testBlobUpload() throws Exception {
    String postData = "--==boundary\r\n" + "Content-Type: message/external-body; "
            + "charset=ISO-8859-1; blob-key=\"blobkey:blob-0\"\r\n" + "Content-Disposition: form-data; "
            + "name=upload-0; filename=\"file-0.jpg\"\r\n" + "\r\n" + "Content-Type: image/jpeg\r\n"
            + "Content-Length: 1024\r\n" + "X-AppEngine-Upload-Creation: 2009-04-30 17:12:51.675929\r\n"
            + "Content-Disposition: form-data; " + "name=upload-0; filename=\"file-0.jpg\"\r\n" + "\r\n"
            + "\r\n" + "--==boundary\r\n" + "Content-Type: text/plain; charset=ISO-8859-1\r\n"
            + "Content-Disposition: form-data; name=text1\r\n" + "Content-Length: 10\r\n" + "\r\n"
            + "Testing.\r\n" + "\r\n" + "\r\n" + "--==boundary--";

    HttpClient httpClient = new HttpClient();
    httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(30000);
    PostMethod blobPost = new PostMethod(createUrl("/upload-blob").toString());
    blobPost.addRequestHeader("Content-Type", "multipart/form-data; boundary=\"==boundary\"");
    blobPost.addRequestHeader("X-AppEngine-BlobUpload", "true");
    blobPost.setRequestBody(postData);
    int httpCode = httpClient.executeMethod(blobPost);

    assertEquals(302, httpCode);
    Header redirUrl = blobPost.getResponseHeader("Location");
    assertEquals("http://" + getServerHost() + "/serve-blob?key=blobkey:blob-0", redirUrl.getValue());
}

From source file:ccc.api.http.SiteBrowserImpl.java

/** {@inheritDoc} */
@Override/*from   ww  w. j  a va2 s  .c o m*/
public String postMultipart(final ResourceSummary rs, final Map<String, String> params) {
    /* This method deliberately elides charset values to replicate the
     * behaviour of a typical browser.                                    */

    final String boundary = UUID.randomUUID().toString().substring(0, 7);
    final String newLine = "\r\n";

    final PostMethod post = new PostMethod(_hostUrl + rs.getAbsolutePath());
    post.setRequestHeader("Content-Type", "multipart/form-data; boundary=" + boundary);

    final StringBuilder buffer = new StringBuilder();
    buffer.append("Content-Type: multipart/form-data");
    buffer.append("; boundary=");
    buffer.append(boundary);
    buffer.append(newLine);
    buffer.append(newLine);
    for (final Map.Entry<String, String> param : params.entrySet()) {
        buffer.append("--");
        buffer.append(boundary);
        buffer.append(newLine);
        buffer.append("Content-Disposition: form-data; name=\"");
        buffer.append(param.getKey());
        buffer.append("\"");
        buffer.append(newLine);
        buffer.append(newLine);
        buffer.append(param.getValue());
        buffer.append(newLine);
    }
    buffer.append("--");
    buffer.append(boundary);
    buffer.append("--");
    buffer.append(newLine);

    post.setRequestEntity(new StringRequestEntity(buffer.toString()));

    return invoke(post);
}

From source file:com.mindquarry.search.serializer.IndexPostSerializer.java

@Override
public void endDocument() throws SAXException {
    super.endDocument();

    Node node = this.res.getNode();
    Element root = (Element) ((Document) node).getFirstChild();
    String action = root.getAttribute("action"); //$NON-NLS-1$

    NodeList children = root.getChildNodes();

    if (true) { // should resolve the action and find out wether it is a
        // cycle through all children of the root element
        for (int i = 0; i < children.getLength(); i++) {
            Node child = children.item(i);
            // for every child element...
            if (child instanceof Element) {

                // block source which can be posted by creating a new
                // servlet request
                URL url = null;//from w w w  .  j ava2 s .  com
                try {
                    url = new URL(action);
                } catch (MalformedURLException e1) {
                    e1.printStackTrace();
                }
                HttpClient client = new HttpClient();
                client.getState().setCredentials(
                        new AuthScope(url.getHost(), url.getPort(), AuthScope.ANY_REALM),
                        new UsernamePasswordCredentials(login, password));

                PostMethod pMethod = new PostMethod(action);
                pMethod.setDoAuthentication(true);
                pMethod.addRequestHeader("accept", "text/xml"); //$NON-NLS-1$ //$NON-NLS-2$

                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                TransformerFactory tf = TransformerFactory.newInstance();
                try {
                    tf.newTransformer().transform(new DOMSource(child), new StreamResult(baos));
                    pMethod.setRequestEntity(new ByteArrayRequestEntity(baos.toByteArray()));
                    client.executeMethod(pMethod);
                } catch (TransformerConfigurationException e) {
                    getLogger().error("Failed to configure transformer prior to posting", e);
                } catch (TransformerException e) {
                    getLogger().error("Failed to transform prior to posting", e);
                } catch (HttpException e) {
                    getLogger().error("Failed to post", e);
                } catch (IOException e) {
                    getLogger().error("Something went wrong", e);
                }
            }
        }
    }
}

From source file:hk.hku.cecid.corvus.http.HttpSenderUnitTest.java

/** Test whether the HTTP sender able to send the HTTP header with POST parameter to our monitor successfully. */
public void testSendWithParameter() throws Exception {
    this.target = new HttpSender(this.testClassLogger, new KVPairData(0)) {

        public HttpMethod onCreateRequest() throws Exception {
            PostMethod method = new PostMethod("http://localhost:1999");
            method.addParameter("testparamName", "testparamValue");
            return method;
        }//from  w  ww  .j  ava  2s  .  c  o  m
    };
    this.assertSend();
}

From source file:JiraWebClient.java

public void addCommentToIssue(final JiraIssue issue, final String comment, IProgressMonitor monitor)
        throws JiraException {
    doInSession(monitor, new JiraWebSessionCallback() {
        @Override/*from   w ww.  j av  a 2s .c o  m*/
        public void run(JiraClient client, String baseUrl, IProgressMonitor monitor) throws JiraException {
            StringBuilder rssUrlBuffer = new StringBuilder(baseUrl);
            rssUrlBuffer.append("/secure/AddComment.jspa"); //$NON-NLS-1$

            PostMethod post = new PostMethod(rssUrlBuffer.toString());
            post.setRequestHeader("Content-Type", getContentType(monitor)); //$NON-NLS-1$
            prepareSecurityToken(post);
            post.addParameter("comment", comment); //$NON-NLS-1$
            post.addParameter("commentLevel", ""); //$NON-NLS-1$ //$NON-NLS-2$
            post.addParameter("id", issue.getId()); //$NON-NLS-1$

            try {
                execute(post);
                if (!expectRedirect(post, "/browse/" + issue.getKey(), false)) { //$NON-NLS-1$
                    handleErrorMessage(post);
                }
            } finally {
                post.releaseConnection();
            }
        }

    });
}

From source file:com.jmeter.alfresco.utils.HttpUtils.java

/**
 * Document upload.// w w  w .j a  v a2s.  c o  m
 *
 * @param docFileObj the doc file obj
 * @param authTicket the auth ticket
 * @param uploadURI the upload uri
 * @param siteID the site id
 * @param uploadDir the upload dir
 * @return the string
 * @throws IOException Signals that an I/O exception has occurred.
 */
public String documentUpload(final File docFileObj, final String authTicket, final String uploadURI,
        final String siteID, final String uploadDir) throws IOException {

    String uploadResponse = Constants.EMPTY;
    PostMethod postRequest = null;
    try {
        final String uploadURL = getFileUploadURL(uploadURI, authTicket);
        LOG.info("documentUpload() | Upload URL: " + uploadURL);

        final HttpClient httpClient = new HttpClient();
        postRequest = new PostMethod(uploadURL);
        final String mimeType = getMimeType(docFileObj);
        final String docName = docFileObj.getName();
        LOG.debug("documentUpload() | Uploading document: " + docName + " , content-type: " + mimeType);

        final Part[] parts = { new FilePart("filedata", docName, docFileObj, mimeType, null),
                new StringPart("filename", docName), new StringPart("overwrite", "true"),
                new StringPart("siteid", siteID),
                new StringPart("containerid", ConfigReader.getProperty(Constants.CONTAINER_ID)),
                new StringPart("uploaddirectory", uploadDir) };

        postRequest.setRequestEntity(new MultipartRequestEntity(parts, postRequest.getParams()));
        final int statusCode = httpClient.executeMethod(postRequest);
        uploadResponse = postRequest.getResponseBodyAsString();
        LOG.info("documentUpload() | Upload status: " + statusCode);
        LOG.debug("documentUpload() | Upload response: " + uploadResponse);
    } finally {
        if (postRequest != null) {
            //releaseConnection http connection
            postRequest.releaseConnection();
        }
    }
    return uploadResponse;
}

From source file:com.cloudmaster.cmp.util.AlarmSystem.transfer.HttpSender.java

public ResponseObject send(Object object, Map<String, String> paramMap) throws Exception {
    ResponseObject rs = new ResponseObject();
    ByteArrayOutputStream bOs = null;
    DataOutputStream dOs = null;/*from ww w  . ja v  a  2s . c  om*/
    DataInputStream dIs = null;
    HttpClient client;
    PostMethod meth = null;
    byte[] rawData;
    try {
        client = new HttpClient();
        client.setConnectionTimeout(this.timeout);
        client.setTimeout(this.datatimeout);
        client.setHttpConnectionFactoryTimeout(this.timeout);

        meth = new PostMethod(paramMap.get("SERVER_URL"));
        // meth = new UTF8PostMethod(url);
        meth.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, ENCODING);
        // meth.addParameter(SERVER_ARGS, new String(rawData,"UTF-8"));
        meth.setRequestBody(object.toString());
        System.out.println(object.toString());

        /**
         * "type"="ruleSync",XML? "syncType"="***"
         * 1??2??3? "ruleName"="***"
         * XML?XML???XML
         */
        meth.addRequestHeader("type", paramMap.get("type"));
        meth.addRequestHeader("syncType", paramMap.get("syncType"));
        meth.addRequestHeader("ruleName", URLEncoder.encode(paramMap.get("ruleName"), "UTF-8"));
        client.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
                new DefaultHttpMethodRetryHandler(1, false));

        client.executeMethod(meth);

        dIs = new DataInputStream(meth.getResponseBodyAsStream());

        if (meth.getStatusCode() == HttpStatus.SC_OK) {

            Header errHeader = meth.getResponseHeader(HDR_ERROR);

            if (errHeader != null) {
                rs.setError(meth.getResponseBodyAsString());
                return rs;
            }

            rs = ResponseObject.fromStream(dIs);

            return rs;
        } else {
            meth.releaseConnection();
            throw new IOException("Connection failure: " + meth.getStatusLine().toString());
        }
    } finally {
        if (meth != null) {
            meth.releaseConnection();
        }
        if (bOs != null) {
            bOs.close();
        }
        if (dOs != null) {
            dOs.close();
        }
        if (dIs != null) {
            dIs.close();
        }
    }
}

From source file:es.carebear.rightmanagement.client.RestClient.java

public void getAllUsersWithAccess() throws IOException {
    HttpClient client = new HttpClient();

    PostMethod deleteMethod = new PostMethod(getServiceBaseURI() + "/client/groups/users/" + "User");

    deleteMethod.addParameter("authName", "Admin");

    int responseCode = client.executeMethod(deleteMethod);

    String response = responseToString(deleteMethod.getResponseBodyAsStream());

    System.out.println(responseCode);

    StringListContainer lc = XMLHelper.fromXML(response, StringListContainer.class);

    lc.getContainer().stream().forEach(w -> {
        System.out.println("ULUMULU" + w);
    });//from w ww .  ja  va  2  s  .  c o m
}

From source file:com.github.rnewson.couchdb.lucene.Database.java

private String post(final String path, final String body) throws HttpException, IOException {
    final PostMethod post = new PostMethod(url(path));
    post.setRequestEntity(new StringRequestEntity(body, "application/json", "UTF-8"));
    return execute(post);
}

From source file:it.unibz.instasearch.ui.ReportErrorDialog.java

/**
 * @throws IOException //w  ww.  j  a  v  a2 s. c  o m
 * @throws HttpException 
 * 
 */
private void reportError() throws HttpException, IOException {
    HttpClient httpClient = new HttpClient();
    PostMethod postMethod = new PostMethod(InstaSearchPlugin.getErrorReportURL());

    postMethod.addParameter("subj", message);
    postMethod.addParameter("attn", "Exception");
    postMethod.addParameter("notes", getStatusContent(status));
    postMethod.addParameter("visitor", "InstaSearch Plugin " + InstaSearchPlugin.getVersion());

    httpClient.executeMethod(postMethod);

    postMethod.releaseConnection();
}