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:hk.hku.cecid.corvus.http.HttpSenderUnitTest.java

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

        public HttpMethod onCreateRequest() throws Exception {
            PostMethod method = new PostMethod("http://localhost:1999");
            Part[] parts = { new StringPart("testparamName", "testparamValue") };
            method.setRequestEntity(new MultipartRequestEntity(parts, method.getParams()));
            return method;
        }//  w  ww.j av  a  2 s . c  o  m
    };
    this.assertSend();
}

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

@Test
public void testMultiplePost() throws Exception {

    HttpClient client = new HttpClient();
    client.getParams().setParameter(HttpProtocolParams.PROTOCOL_VERSION, HttpVersion.HTTP_1_0);

    PostMethod post = new PostMethod("http://localhost:3000/axis2/services/BLZService");
    InputStream stream = this.getClass().getResourceAsStream("/getBank.xml");

    InputStreamRequestEntity entity = new InputStreamRequestEntity(stream);
    post.setRequestEntity(entity);
    post.setRequestHeader(Header.CONTENT_TYPE, MimeType.TEXT_XML_UTF8);
    post.setRequestHeader(Header.SOAP_ACTION, "\"\"");

    for (int i = 0; i < 100; i++) {
        //System.out.println("Iteration: " + i);
        int status = client.executeMethod(post);
        assertEquals(200, status);// w w w.  ja  va2  s.  c  o m
        String response = post.getResponseBodyAsString();
        assertNotNull(response);
        assertTrue(response.length() > 0);
    }

}

From source file:com.foglyn.fogbugz.Request.java

Document post(String url, List<Part> parts, IProgressMonitor monitor) throws FogBugzException {
    PostMethod postMethod = new PostMethod(url);
    // postMethod.getParams().setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE, true);
    postMethod.setRequestEntity(new MultipartRequestEntity(parts.toArray(new Part[0]), postMethod.getParams()));

    Document result = request(url, postMethod, monitor, new DocumentResponseProcessor());

    if (checkResponseError) {
        throwExceptionOnError(result);/*from  w ww . ja  v  a  2  s  .c  o  m*/
    }

    return result;
}

From source file:com.cognifide.maven.plugins.crx.CrxPackageAbstractMojo.java

/**
 * Performs post request to given URL with given parameters provided as a part lists.
 * /*from ww  w .j  a  v a 2  s  . c om*/
 * @param targetURL Place where post action should be submitted
 * @param partList Parameters of post action
 * @return Response body
 * @throws MojoExecutionException
 */
protected String post(String targetURL, List<Part> partList) throws MojoExecutionException {
    PostMethod postMethod = new PostMethod(targetURL);

    try {
        Part[] parts = partList.toArray(new Part[partList.size()]);
        postMethod.setRequestEntity(new MultipartRequestEntity(parts, postMethod.getParams()));

        int status = getHttpClient().executeMethod(postMethod);

        if (status == HttpStatus.SC_OK) {
            return IOUtils.toString(postMethod.getResponseBodyAsStream());
        } else {
            getLog().warn(postMethod.getResponseBodyAsString());
            throw new MojoExecutionException("Request to the repository failed, cause: "
                    + HttpStatus.getStatusText(status) + " (check URL, user and password)");
        }

    } catch (IOException ex) {
        throw new MojoExecutionException("Request to the repository failed, cause: " + ex.getMessage(), ex);
    } finally {
        postMethod.releaseConnection();
    }
}

From source file:edina.eframework.gefcdemo.controllers.ProcessErosionController.java

/**
 * Brokers the WPS request and response. Supports two different WPS requests,
 * the landcover preview and the process soil erosion model requests.
 * //from  w  w w  . jav  a  2 s . c om
 * @param params parameters used when calculating the soil erosion model
 * @param wpsResponse results from the WPS process are written to this object
 * @param template the VM template to use to generate the WPS request
 * @param wpsOutputFile the filename to write the TIFF result file
 * @throws IOException
 * @throws JAXBException
 */
private void generateWpsRequest(SoilErosionWps params, WpsResponse wpsResponse, String template,
        String wpsOutputFile) throws IOException, JAXBException {

    Writer wpsRequest = new StringWriter();
    Map<String, Object> velocityMap = new HashMap<String, Object>();

    velocityMap.put("params", params);

    VelocityEngineUtils.mergeTemplate(velocityEngine, template, velocityMap, wpsRequest);
    wpsRequest.close();

    log.debug(wpsRequest.toString());
    log.debug("Submitting to " + wpsServer);

    RequestEntity entity = null;
    try {
        entity = new StringRequestEntity(wpsRequest.toString(), "text/xml", "UTF-8");
    } catch (UnsupportedEncodingException e) {
        throw new MalformedURLException("Apparantly 'UTF-8' is an unsupported encoding type.");
    }

    PostMethod post = new PostMethod(wpsServer.toString());
    post.setRequestEntity(entity);

    HttpClient client = new HttpClient(new SimpleHttpConnectionManager());

    client.getHttpConnectionManager().getParams().setSoTimeout(0);
    client.getHttpConnectionManager().getParams().setConnectionTimeout(0);

    client.executeMethod(post);

    JAXBContext jaxbContext = JAXBContext.newInstance("edina.eframework.gefcdemo.generated.wps");
    Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();

    ExecuteResponse executeResponse = null;
    // First save post data into a String so we can log any potential errors.
    // Response isn't very large from the WPS so this shouldn't be a problem.
    // Trying to access post data if a direct InputStream is passed to unmarshal
    // doesn't work.
    String postData = post.getResponseBodyAsString();
    try {
        executeResponse = (ExecuteResponse) unmarshaller
                .unmarshal(new ByteArrayInputStream(postData.getBytes()));
    } catch (ClassCastException e) {
        log.error("Error from WPS:\n" + postData);
        throw e;
    }

    //executeResponse.getStatus().getProcessAccepted(); // TODO check for failed
    String resultUrl = executeResponse.getProcessOutputs().getOutput().get(0).getReference().getHref();

    log.debug("Output " + resultUrl);
    wpsResponse.setOutputUrl(new URL(resultUrl));
    wpsResponse.setOutputId(resultUrl.substring(resultUrl.lastIndexOf("id=") + 3, resultUrl.length()));
    wpsResponse.setStatus(200);

    // Save the WPS output data to a file mapserver can use
    File resultOutputFile = new File(wpsOutputFile);
    resultOutputFile.getParentFile().mkdirs();
    FileOutputStream resultFileStream = new FileOutputStream(resultOutputFile);
    InputStream resultInputFile = null;
    try {
        resultInputFile = wpsResponse.getOutputUrl().openStream();
        byte[] buffer = new byte[4096];
        int i;
        while ((i = resultInputFile.read(buffer)) != -1) {
            resultFileStream.write(buffer, 0, i);
        }
        resultFileStream.flush();
    } finally {
        try {
            resultInputFile.close();
        } catch (Exception e) {
        }
        try {
            resultFileStream.close();
        } catch (Exception e) {
        }
    }

    log.debug("Result saved to " + resultOutputFile);
}

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

/**
 * Test that can import into a new calendar from ICALENDAR containing an inline ATTACHment.
 * Test that it is possible to export calendar entry with an attachment with the attachment
 * inlined if icalAttach=inline or ignoring the attachment if icalAttach=none
 *///from w w w.  j a  va2 s.c o  m
public void testIcsImportExport() throws IOException, ValidationException, ServiceException {
    ZMailbox mbox = TestUtil.getZMailbox(USER_NAME);
    String calName = NAME_PREFIX + "2ndCalendar";
    String calUri = String.format("/%s?fmt=ics", calName);
    TestUtil.createFolder(mbox, calName, ZFolder.View.appointment);
    net.fortuna.ical4j.model.Calendar calendar = new net.fortuna.ical4j.model.Calendar();
    calendar.getProperties().add(new ProdId("-//ZimbraTest 1.0//EN"));
    calendar.getProperties().add(Version.VERSION_2_0);
    calendar.getProperties().add(CalScale.GREGORIAN);
    java.util.Calendar start = java.util.Calendar.getInstance();
    start.set(java.util.Calendar.MONTH, java.util.Calendar.SEPTEMBER);
    start.set(java.util.Calendar.DAY_OF_MONTH, 03);

    VEvent wwII = new VEvent(new Date(start.getTime()), NAME_PREFIX + " Declarations of war");
    wwII.getProperties().getProperty(Property.DTSTART).getParameters().add(Value.DATE);
    wwII.getProperties().add(new Uid("3-14159"));
    Attach attach = new Attach("Attachment.\nIsn't it short.".getBytes(MimeConstants.P_CHARSET_ASCII));
    attach.getParameters().add(new XParameter("X-APPLE-FILENAME", "short.txt"));
    attach.getParameters().add(new FmtType(MimeConstants.CT_TEXT_PLAIN));
    wwII.getProperties().add(attach);
    calendar.getComponents().add(wwII);
    ByteArrayOutputStream buf = new ByteArrayOutputStream();
    CalendarOutputter outputter = new CalendarOutputter();
    outputter.setValidating(false);
    outputter.output(calendar, buf);
    URI uri = mbox.getRestURI(calUri);
    HttpClient client = mbox.getHttpClient(uri);
    PostMethod post = new PostMethod(uri.toString());
    post.setRequestEntity(new InputStreamRequestEntity(new ByteArrayInputStream(buf.toByteArray()),
            MimeConstants.CT_TEXT_CALENDAR));
    ZimbraLog.test.info("testIcsImportExport:ICS to be imported:%s", new String(buf.toByteArray()));
    TestCalDav.HttpMethodExecutor.execute(client, post, HttpStatus.SC_OK);
    uri = mbox.getRestURI(calUri + "&icalAttach=inline");
    GetMethod get = new GetMethod(uri.toString());
    TestCalDav.HttpMethodExecutor executor = new TestCalDav.HttpMethodExecutor(client, get, HttpStatus.SC_OK);
    String respIcal = new String(executor.responseBodyBytes, MimeConstants.P_CHARSET_UTF8);
    ZimbraLog.test.info("testIcsImportExport:ICS exported (with icalAttach=inline):%s", respIcal);
    int attachNdx = respIcal.indexOf("ATTACH;");
    assertTrue("ATTACH should be present", -1 != attachNdx);
    String fromAttach = respIcal.substring(attachNdx);
    assertTrue("BINARY should be present", -1 != fromAttach.indexOf("VALUE=BINARY"));
    uri = mbox.getRestURI(calUri + "&icalAttach=none");
    get = new GetMethod(uri.toString());
    executor = new TestCalDav.HttpMethodExecutor(client, get, HttpStatus.SC_OK);
    respIcal = new String(executor.responseBodyBytes, MimeConstants.P_CHARSET_UTF8);
    ZimbraLog.test.debug("testIcsImportExport:ICS exported (with icalAttach=none):%s", respIcal);
    assertTrue("ATTACH should be present", -1 == respIcal.indexOf("ATTACH;"));
    uri = mbox.getRestURI(calUri);
    get = new GetMethod(uri.toString());
    executor = new TestCalDav.HttpMethodExecutor(client, get, HttpStatus.SC_OK);
    respIcal = new String(executor.responseBodyBytes, MimeConstants.P_CHARSET_UTF8);
    ZimbraLog.test.debug("testIcsImportExport:ICS exported (default - same as icalAttach=none):%s", respIcal);
    assertTrue("ATTACH should be present", -1 == respIcal.indexOf("ATTACH;"));
}

From source file:demo.jaxrs.client.Client.java

public void addCustomerInfo(String name, String password) throws Exception {

    System.out.println("HTTP POST to add customer info, user : " + name + ", password : " + password);
    PostMethod post = new PostMethod("http://localhost:9002/customerservice/customers");
    setMethodHeaders(post, name, password);
    RequestEntity entity = new InputStreamRequestEntity(
            this.getClass().getClassLoader().getResourceAsStream("add_customer.xml"));
    post.setRequestEntity(entity);

    handleHttpMethod(post);/*from w w w .  j a v  a  2  s  .c om*/
}

From source file:ch.ksfx.web.services.spidering.http.HttpClientHelper.java

/**
 * Returns an executed PostMethod object with the given URL and the given
 * RequestEntity object in the request body
 *
 * @param url URL for HTTP POST request/*from  ww  w  .j  a  v a  2s . co  m*/
 * @param requestEntity RequestEntity for request body
 * @return executed PostMethod object
 */
public PostMethod executePostMethod(String url, RequestEntity requestEntity) {
    try {
        url = encodeURL(url);
        PostMethod postMethod = new PostMethod(url);
        if (requestEntity != null) {
            postMethod.setFollowRedirects(false);
            postMethod.setRequestEntity(requestEntity);
        } else {
            postMethod.setFollowRedirects(true);
        }
        postMethod = (PostMethod) executeMethod(postMethod);
        return postMethod;
    } catch (Exception e) {
        logger.severe("Error while generating POST method: " + e);
        return null;
    }
}

From source file:com.kagilum.plugins.icescrum.IceScrumSession.java

public boolean sendBuildStatut(JSONObject build) throws UnsupportedEncodingException {
    PostMethod method = new PostMethod(settings.getUrl() + "/ws/p/" + settings.getPkey() + "/build");
    StringRequestEntity requestEntity = new StringRequestEntity(build.toString(), "application/json", "UTF-8");
    method.setRequestEntity(requestEntity);
    return executeMethod(method, HttpStatus.SC_CREATED);
}

From source file:net.bpelunit.framework.control.deploy.ode.ODEDeployer.java

public void undeploy(String testPath, ProcessUnderTest put) throws DeploymentException {

    HttpClient client = new HttpClient(new NoPersistenceConnectionManager());
    PostMethod method = new PostMethod(fDeploymentAdminServiceURL);

    RequestEntity re = fFactory.getUndeployRequestEntity(fProcessId);
    method.setRequestEntity(re);

    LOGGER.info("ODE deployer about to send SOAP request to undeploy " + put);

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

    int statusCode = 0;
    String responseBody = null;//  w  w  w  .  j  av a2s.c o m
    try {
        statusCode = client.executeMethod(method);
        responseBody = method.getResponseBodyAsString();
    } catch (Exception e) {
        throw new DeploymentException("Problem contacting the ODE Server: " + e.getMessage(), e);
    } finally {
        method.releaseConnection();
    }

    if (isHttpErrorCode(statusCode)) {
        throw new DeploymentException("ODE Server reported a undeployment Error: " + responseBody);
    }
}