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:muki.tool.JavaCompilationDeploymentTestCase.java

@Test
public void testPostOperationInvalidCharsXml() throws Exception {
    String url = URL_RESOURCE2 + "/pathPostOperationInvalidCharsXml";
    PostMethod method = new PostMethod(url);
    String param = this.getXmlTrackInvalidChars();
    method.setRequestEntity(new StringRequestEntity(param, "application/xml", null));

    int statusCode = this.getHttpClient().executeMethod(method);
    assertTrue("Method failed: " + method.getStatusLine(), statusCode == HttpStatus.SC_OK);
    byte[] responseBody = method.getResponseBody();
    String xmlResponse = new String(responseBody);
    assertTrue(xmlResponse.indexOf("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>") > -1);
    assertTrue(xmlResponse.indexOf("<title>&lt;My Track 1/&gt; &amp; 'My Track' &quot;2&quot;</title>") > -1);
}

From source file:muki.tool.JavaCompilationDeploymentTestCase.java

/**
 * The JSON string contains special chars in the values: '{', '}', '"' that must
 * be enconded and arrive correctly on the server.
 *///from   w w w. ja v  a2s. c  om
@Test
public void testPostOperationInvalidCharsJson() throws Exception {
    String url = URL_RESOURCE2 + "/pathPostOperationInvalidCharsJson";
    PostMethod method = new PostMethod(url);
    String param = this.getJsonTrackInvalidChars();
    method.setRequestEntity(new StringRequestEntity(param, "application/json", null));

    int statusCode = this.getHttpClient().executeMethod(method);
    assertTrue("Method failed: " + method.getStatusLine(), statusCode == HttpStatus.SC_OK);
    byte[] responseBody = method.getResponseBody();
    String jsonResponse = new String(responseBody);
    assertTrue(jsonResponse.indexOf("{My {\\\"Track} 1 & {'My Track' ") > -1);
}

From source file:edu.wisc.ssec.mcidasv.supportform.Submitter.java

/**
 * Attempts to {@code POST} to {@code url} using the information from 
 * {@code form}.//from   w w w  .j a va2 s.  co  m
 * 
 * @param url URL that'll accept the {@code POST}. Typically 
 * {@link #requestUrl}.
 * @param form The {@link SupportForm} that contains the data to use in the
 * support request.
 * 
 * @return Big honkin' object that contains the support request.
 */
private static PostMethod buildPostMethod(String url, SupportForm form) {
    PostMethod method = new PostMethod(url);

    List<Part> parts = new ArrayList<Part>();
    parts.add(new StringPart("form_data[fromName]", form.getUser()));
    parts.add(new StringPart("form_data[email]", form.getEmail()));
    parts.add(new StringPart("form_data[organization]", form.getOrganization()));
    parts.add(new StringPart("form_data[subject]", form.getSubject()));
    parts.add(new StringPart("form_data[description]", form.getDescription()));
    parts.add(new StringPart("form_data[submit]", ""));
    parts.add(new StringPart("form_data[p_version]", "p_version=ignored"));
    parts.add(new StringPart("form_data[opsys]", "opsys=ignored"));
    parts.add(new StringPart("form_data[hardware]", "hardware=ignored"));
    parts.add(new StringPart("form_data[cc_user]", Boolean.toString(form.getSendCopy())));

    // attach the files the user has explicitly attached.
    if (form.hasAttachmentOne()) {
        parts.add(buildRealFilePart("form_data[att_two]", form.getAttachmentOne()));
    }
    if (form.hasAttachmentTwo()) {
        parts.add(buildRealFilePart("form_data[att_three]", form.getAttachmentTwo()));
    }
    // if the user wants, attach an XML bundle of the state
    if (form.canBundleState() && form.getSendBundle()) {
        parts.add(
                buildFakeFilePart("form_data[att_state]", form.getBundledStateName(), form.getBundledState()));
    }

    // attach system properties
    parts.add(buildFakeFilePart("form_data[att_extra]", form.getExtraStateName(), form.getExtraState()));

    // attach mcidasv.log (if it exists)
    if (form.canSendLog()) {
        parts.add(buildRealFilePart("form_data[att_log]", form.getLogPath()));
    }

    // attach RESOLV.SRV (if it exists)
    if (form.canSendResolvSrv()) {
        parts.add(buildRealFilePart("form_data[att_resolvsrv]", form.getResolvSrvPath()));
    }

    // tack on the contents of runMcV.prefs
    parts.add(buildRealFilePart("form_data[att_prefs]", form.getPrefsPath()));

    Part[] arr = parts.toArray(new Part[0]);
    MultipartRequestEntity mpr = new MultipartRequestEntity(arr, method.getParams());
    method.setRequestEntity(mpr);
    return method;
}

From source file:com.ephesoft.dcma.boxexport.BoxExporter.java

/**
 * Method to process each document of the batch instance and export corresponding files to the box repository.
 * /*w  w  w . j  a v a 2s  .  c o m*/
 * @param batchInstanceIdentifier {@link String}
 * @param folderID {@link String}
 * @param authToken {@link String}
 * @param boxUploadFileType {@link String}
 * @param sFolderToBeExported {@link String}
 * @param listOfDocuments {@link List<Document>}
 * @throws DCMAApplicationException {@link DCMAApplicationException}
 */
private void processDocuments(final String batchInstanceIdentifier, final String folderID,
        final String authToken, final String boxUploadFileType, final String sFolderToBeExported,
        final List<Document> listOfDocuments) throws DCMAApplicationException {
    String exportMultiPageFileName = null;
    String url = BoxExportConstant.HTTPS_WWW_BOX_COM_API_1_0_UPLOAD_URL
            .replace(BoxExportConstant.AUTH_TOKEN_CONSTANT, authToken)
            .replace(BoxExportConstant.FOLDER_ID_CONSTANT, folderID);
    HttpClient client = new HttpClient();
    PostMethod mPost = new PostMethod(url);
    try {
        for (Document document : listOfDocuments) {
            LOGGER.info("Processing document for box export : " + document.getIdentifier());
            if (boxUploadFileType.equalsIgnoreCase(BoxExportConstant.MULTIPAGE_PDF)) {
                exportMultiPageFileName = document.getMultiPagePdfFile();
            } else {
                exportMultiPageFileName = document.getMultiPageTiffFile();
            }

            LOGGER.info("The file to be exported is : " + exportMultiPageFileName);
            File exportFile = new File(sFolderToBeExported + File.separator + exportMultiPageFileName);

            // Creating the data to be exported to Box
            Part[] parts = new Part[2];
            parts[0] = new FilePart(exportMultiPageFileName, exportFile);
            String docLevelFieldData = getDocLevelFieldsData(document);
            LOGGER.info("Description for uploading file : " + docLevelFieldData);
            parts[1] = new StringPart(BoxExportConstant.DESCRIPTION, docLevelFieldData);

            MultipartRequestEntity entity = new MultipartRequestEntity(parts, mPost.getParams());
            mPost.setRequestEntity(entity);

            // Sending the data to Box
            int statusCode = client.executeMethod(mPost);
            LOGGER.info("Status Code of method execution: " + statusCode);
            String responseBody = mPost.getResponseBodyAsString();
            LOGGER.info("responseBody :: " + responseBody);

            // Getting and analyzing the response for the sent data
            org.w3c.dom.Document doc = XMLUtil.createDocumentFrom(mPost.getResponseBodyAsStream());
            String statusOfResponse = XMLUtil.getValueFromXML(doc, BoxExportConstant.RESPONSE_STATUS);
            LOGGER.info("The status of response for upload is :" + statusOfResponse);
            if (null == statusOfResponse || !statusOfResponse.equals(BoxExportConstant.UPLOAD_OK)) {
                LOGGER.error("Error uploading files to Box. Exiting with error code : " + statusCode);
                throw new DCMAApplicationException(ERROR_EXPORTING_FILE + exportMultiPageFileName
                        + BATCH_INSTANCE_ID + batchInstanceIdentifier);
            }
        }
    } catch (Exception e) {
        LOGGER.error(
                ERROR_EXPORTING_FILE + exportMultiPageFileName + BATCH_INSTANCE_ID + batchInstanceIdentifier,
                e);
        throw new DCMAApplicationException(
                ERROR_EXPORTING_FILE + exportMultiPageFileName + BATCH_INSTANCE_ID + batchInstanceIdentifier,
                e);
    } finally {
        mPost.releaseConnection();
    }
}

From source file:net.bpelunit.framework.control.run.TestCaseRunner.java

/**
 * /*from  w  w  w. java  2s. c  o m*/
 * Sends a synchronous message, waits for the result, and returns the
 * result. This method blocks until either a result has been retrieved, a
 * send error has occurred, or the thread was interrupted.
 * 
 * @param message
 *            the message to be sent
 * @return the resulting incoming message
 * @throws SynchronousSendException
 * @throws InterruptedException
 */
public IncomingMessage sendMessageSynchronous(OutgoingMessage message)
        throws SynchronousSendException, InterruptedException {
    PostMethod method = new PostMethod(message.getTargetURL());

    // Set parameters:
    // -> Do not retry
    // -> Socket timeout to default timeout value.
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(1, false));
    method.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, Integer.valueOf(BPELUnitRunner.getTimeout()));

    method.addRequestHeader("SOAPAction", "\"" + message.getSOAPHTTPAction() + "\"");
    RequestEntity entity;
    try {
        entity = new StringRequestEntity(message.getMessageAsString(), BPELUnitConstants.TEXT_XML_CONTENT_TYPE,
                BPELUnitConstants.DEFAULT_HTTP_CHARSET);
    } catch (UnsupportedEncodingException e) {
        // cannot happen since we use the default HTTP Encoding.
        throw new SynchronousSendException("Unsupported encoding when trying to post message to web service.",
                e);
    }

    for (String option : message.getProtocolOptionNames()) {
        method.addRequestHeader(option, message.getProtocolOption(option));
    }
    method.setRequestEntity(entity);

    try {
        // Execute the method.

        int statusCode = fClient.executeMethod(method);
        InputStream in = method.getResponseBodyAsStream();

        IncomingMessage returnMsg = new IncomingMessage();
        returnMsg.setStatusCode(statusCode);
        returnMsg.setMessage(in);

        return returnMsg;

    } catch (Exception e) {
        if (isAborting()) {
            throw new InterruptedException();
        } else {
            throw new SynchronousSendException(e);
        }
    } finally {
        // Release the connection.
        method.releaseConnection();
    }

}

From source file:eu.eco2clouds.scheduler.accounting.client.AccountingClientHC.java

private String postMethod(String url, String payload, String bonfireUserId, String bonfireGroupId,
        Boolean exception) {/*from   w ww.  jav a 2 s .com*/
    // Create an instance of HttpClient.
    HttpClient client = getHttpClient();

    logger.debug("Connecting to: " + url);
    // Create a method instance.
    PostMethod method = new PostMethod(url);
    setHeaders(method, bonfireGroupId, bonfireUserId);
    //method.addRequestHeader("Content-Type", SchedulerDictionary.CONTENT_TYPE_ECO2CLOUDS_XML);

    // Provide custom retry handler is necessary
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(3, false));

    String response = "";

    try {
        // We set the payload
        StringRequestEntity payloadEntity = new StringRequestEntity(payload,
                SchedulerDictionary.CONTENT_TYPE_ECO2CLOUDS_XML, "UTF-8");
        method.setRequestEntity(payloadEntity);

        // Execute the method.
        int statusCode = client.executeMethod(method);
        logger.debug("Status Code: " + statusCode);

        if (statusCode >= 200 && statusCode > 300) { //TODO test for this case... 
            logger.warn("Get host information of testbeds: " + url + " failed: " + method.getStatusLine());
        } else {
            // Read the response body.
            byte[] responseBody = method.getResponseBody();
            response = new String(responseBody);
        }

    } catch (HttpException e) {
        logger.warn("Fatal protocol violation: " + e.getMessage());
        e.printStackTrace();
        exception = true;
    } catch (IOException e) {
        logger.warn("Fatal transport error: " + e.getMessage());
        e.printStackTrace();
        exception = true;
    } finally {
        // Release the connection.
        method.releaseConnection();
    }

    return response;
}

From source file:com.ephesoft.dcma.batch.status.StatusConveyor.java

/**
 * Notifies any service event to fired on current server but needs to be handled by the server under which the service is
 * registered. It hits the particular server with the details required and registered server handles it respectively.
 * /*from   w w w.j a  v  a  2s. co  m*/
 * @param paramMap {@link Map<String, String>} details to be send to the server.
 * @param serviceType {@link ServiceType} type of service.
 */
public void notifyServiceEvent(final Map<String, String> paramMap, final ServiceType serviceType) {
    if (null != serviceType) {
        LOGGER.debug(EphesoftStringUtil.concatenate("Notifying server for service: ", serviceType.toString()));
        final String notifyWebServiceUrl = getNotifyWebServiceUrl(serviceType);
        if (null != notifyWebServiceUrl && !notifyWebServiceUrl.isEmpty()) {
            final HttpClient httpClient = new HttpClient();
            final PostMethod postMethod = new PostMethod(notifyWebServiceUrl);
            Part[] partArray = null;
            int index = 0;

            // If the details are to be send to web service
            if (null == paramMap || paramMap.isEmpty()) {
                partArray = new Part[1];
            } else {
                LOGGER.debug(EphesoftStringUtil.concatenate("Parameter passed are: ", paramMap.toString()));
                partArray = new Part[(paramMap.size() + 1)];
                final Iterator<String> keyIterator = paramMap.keySet().iterator();
                String key = null;
                while (keyIterator.hasNext()) {
                    key = keyIterator.next();
                    partArray[index] = new StringPart(key, paramMap.get(key));
                    index++;
                }
            }

            // Type of service which is a required parameter to be send
            partArray[index] = new StringPart(ICommonConstants.SERVICE_TYPE_PARAMETER,
                    String.valueOf(serviceType.getServiceType()));
            MultipartRequestEntity entity = new MultipartRequestEntity(partArray, postMethod.getParams());
            postMethod.setRequestEntity(entity);
            try {
                int statusCode = httpClient.executeMethod(postMethod);

                if (statusCode == STATUS_OK) {
                    LOGGER.debug(EphesoftStringUtil.concatenate(
                            "Server was notified successfully for service: ", serviceType.toString()));
                } else {
                    LOGGER.error(
                            EphesoftStringUtil.concatenate("Server was not able to be notified for service: ",
                                    serviceType.toString(), " and status code: ", statusCode));
                }
            } catch (HttpException httpException) {
                LOGGER.error(
                        EphesoftStringUtil.concatenate("Could not connect to server for notifying service: ",
                                serviceType.toString(), ICommonConstants.SPACE, httpException.getMessage()));
            } catch (IOException ioException) {
                LOGGER.error(
                        EphesoftStringUtil.concatenate("Could not connect to server for notifying service: ",
                                serviceType.toString(), ICommonConstants.SPACE, ioException.getMessage()));
            }
        }
    }
}

From source file:com.sun.faban.driver.transport.hc3.ApacheHC3Transport.java

/**
 * Makes a Multi-part POST request to the URL. Reads data back and discards
 * the data, keeping just the size of the total read. This is useful for
 * ensuring receival of binary or text data that do not need further
 * analysis.//w  w w .j  av  a2 s .c  o  m
 *
 * @param url The URL to read from
 * @param parts The parts list
 * @param headers The request headers
 * @return The number of bytes read
 * @throws java.io.IOException
 */
public int readURL(String url, List<Part> parts, Map<String, String> headers) throws IOException {

    Part[] partsArray = parts.toArray(new Part[parts.size()]);
    PostMethod method = new PostMethod(url);
    method.setFollowRedirects(followRedirects);
    setHeaders(method, headers);
    method.setRequestEntity(new MultipartRequestEntity(partsArray, method.getParams()));
    try {
        responseCode = hc.executeMethod(method);
        buildResponseHeaders(method);
        return readResponse(method);
    } finally {
        method.releaseConnection();
    }
}

From source file:com.sun.faban.driver.transport.hc3.ApacheHC3Transport.java

/**
 * Makes a Multi-part POST request to the URL. Reads data back and
 * returns the data read. Note that this method only works with text
 * data as it does the byte-to-char conversion. This method will return
 * null for responses with binary MIME types. The addTextType(String)
 * method is used to register additional MIME types as text types.
 * Use getContentSize() to obtain the bytes of binary data read.
 *
 * @param url The URL to read from/*from w w w .ja  va2  s. c  o  m*/
 * @param parts The parts list
 * @param headers The request headers
 * @return The StringBuilder buffer containing the resulting document
 * @throws java.io.IOException
 */
public StringBuilder fetchURL(String url, List<Part> parts, Map<String, String> headers) throws IOException {

    Part[] partsArray = parts.toArray(new Part[parts.size()]);
    PostMethod method = new PostMethod(url);
    method.setFollowRedirects(followRedirects);
    setHeaders(method, headers);
    method.setRequestEntity(new MultipartRequestEntity(partsArray, method.getParams()));
    try {
        responseCode = hc.executeMethod(method);
        buildResponseHeaders(method);
        return fetchResponse(method);
    } finally {
        method.releaseConnection();
    }
}

From source file:edu.ku.brc.util.WebStoreAttachmentMgr.java

/**
 * @param targetFile// w  ww  . ja  v  a 2s.  com
 * @param fileName
 * @param isThumb
 * @return
 */
private synchronized boolean sendFile(final File targetFile, final String fileName,
        final boolean isThumb)/*,
                              final boolean saveInCache)*/
{
    String targetURL = writeURLStr;
    PostMethod filePost = new PostMethod(targetURL);

    fillValuesArray();

    try {
        log.debug("Uploading " + targetFile.getName() + " to " + targetURL);

        Part[] parts = { new FilePart(targetFile.getName(), targetFile),
                new StringPart("type", isThumb ? "T" : "O"), new StringPart("store", fileName),
                new StringPart("token", generateToken(fileName)), new StringPart("coll", values[0]),
                new StringPart("disp", values[1]), new StringPart("div", values[2]),
                new StringPart("inst", values[3]), };

        filePost.setRequestEntity(new MultipartRequestEntity(parts, filePost.getParams()));
        HttpClient client = new HttpClient();
        client.getHttpConnectionManager().getParams().setConnectionTimeout(5000);

        int status = client.executeMethod(filePost);
        updateServerTimeDelta(filePost);

        //log.debug("---------------------------------------------------");
        log.debug(filePost.getResponseBodyAsString());
        //log.debug("---------------------------------------------------");

        if (status == HttpStatus.SC_OK) {
            return true;
        }

    } catch (Exception ex) {
        log.error("Error:  " + ex.getMessage());
        ex.printStackTrace();

    } finally {
        filePost.releaseConnection();
    }
    return false;
}