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:net.jadler.JadlerMockingIntegrationTest.java

@Test
public void havingUTF8Body() throws Exception {
    final PostMethod method = new PostMethod("http://localhost:" + port());
    method.setRequestEntity(
            new StringRequestEntity(STRING_WITH_DIACRITICS, "text/plain", UTF_8_CHARSET.name()));

    client.executeMethod(method);//from w w  w  .ja  v a 2 s. c  om

    verifyThatRequest().havingBodyEqualTo(STRING_WITH_DIACRITICS).havingRawBodyEqualTo(UTF_8_REPRESENTATION)
            .receivedOnce();
}

From source file:net.jadler.JadlerMockingIntegrationTest.java

@Test
public void havingISOBody() throws Exception {
    final PostMethod method = new PostMethod("http://localhost:" + port());
    method.setRequestEntity(
            new StringRequestEntity(STRING_WITH_DIACRITICS, "text/plain", ISO_8859_2_CHARSET.name()));

    client.executeMethod(method);//from w w  w. j  a  v a  2 s  . c  o m

    verifyThatRequest().havingBodyEqualTo(STRING_WITH_DIACRITICS)
            .havingRawBodyEqualTo(ISO_8859_2_REPRESENTATION).receivedOnce();
}

From source file:com.bluexml.side.framework.alfresco.webscriptExtension.SiteScriptExtension.java

/**
 * Creates POST method with passed in body and content type
 *
 * @param url         URL for request//w w  w.  j  a  v  a 2  s.  c o m
 * @param body        body of request
 * @param contentType content type of request
 * @return POST method
 * @throws java.io.UnsupportedEncodingException
 *
 */
private PostMethod createPostMethod(String url, String body, String contentType)
        throws UnsupportedEncodingException {
    PostMethod postMethod = new PostMethod(url);
    postMethod.setRequestHeader(HEADER_CONTENT_TYPE, contentType);
    postMethod.setRequestEntity(new StringRequestEntity(body, CONTENT_TYPE_TEXT_PLAIN, UTF_8));

    return postMethod;
}

From source file:com.twinsoft.convertigo.engine.admin.services.mobiles.LaunchBuild.java

@Override
protected void getServiceResult(HttpServletRequest request, Document document) throws Exception {
    synchronized (buildLock) {
        final MobileResourceHelper mobileResourceHelper = new MobileResourceHelper(request, "mobile/www");
        MobileApplication mobileApplication = mobileResourceHelper.mobileApplication;

        if (mobileApplication == null) {
            throw new ServiceException("no such mobile application");
        } else {/*  w w w  .  j av a  2  s  .c  om*/
            boolean bAdminRole = Engine.authenticatedSessionManager.hasRole(request.getSession(),
                    Role.WEB_ADMIN);
            if (!bAdminRole && mobileApplication.getAccessibility() == Accessibility.Private) {
                throw new AuthenticationException("Authentication failure: user has not sufficient rights!");
            }
        }

        MobilePlatform mobilePlatform = mobileResourceHelper.mobilePlatform;

        String finalApplicationName = mobileApplication.getComputedApplicationName();
        File mobileArchiveFile = mobileResourceHelper.makeZipPackage();

        // Login to the mobile builder platform
        String mobileBuilderPlatformURL = EnginePropertiesManager
                .getProperty(PropertyName.MOBILE_BUILDER_PLATFORM_URL);

        Map<String, String[]> params = new HashMap<String, String[]>();

        params.put("application", new String[] { finalApplicationName });
        params.put("platformName", new String[] { mobilePlatform.getName() });
        params.put("platformType", new String[] { mobilePlatform.getType() });
        params.put("auth_token", new String[] { mobileApplication.getComputedAuthenticationToken() });

        //revision and endpoint params
        params.put("revision", new String[] { mobileResourceHelper.getRevision() });
        params.put("endpoint", new String[] { mobileApplication.getComputedEndpoint(request) });

        //iOS
        if (mobilePlatform instanceof IOs) {
            IOs ios = (IOs) mobilePlatform;

            String pw, title = ios.getiOSCertificateTitle();

            if (!title.equals("")) {
                pw = ios.getiOSCertificatePw();
            } else {
                title = EnginePropertiesManager.getProperty(PropertyName.MOBILE_BUILDER_IOS_CERTIFICATE_TITLE);
                pw = EnginePropertiesManager.getProperty(PropertyName.MOBILE_BUILDER_IOS_CERTIFICATE_PW);
            }

            params.put("iOSCertificateTitle", new String[] { title });
            params.put("iOSCertificatePw", new String[] { pw });
        }

        //Android
        if (mobilePlatform instanceof Android) {
            Android android = (Android) mobilePlatform;

            String certificatePw, keystorePw, title = android.getAndroidCertificateTitle();

            if (!title.equals("")) {
                certificatePw = android.getAndroidCertificatePw();
                keystorePw = android.getAndroidKeystorePw();
            } else {
                title = EnginePropertiesManager
                        .getProperty(PropertyName.MOBILE_BUILDER_ANDROID_CERTIFICATE_TITLE);
                certificatePw = EnginePropertiesManager
                        .getProperty(PropertyName.MOBILE_BUILDER_ANDROID_CERTIFICATE_PW);
                keystorePw = EnginePropertiesManager
                        .getProperty(PropertyName.MOBILE_BUILDER_ANDROID_KEYSTORE_PW);
            }

            params.put("androidCertificateTitle", new String[] { title });
            params.put("androidCertificatePw", new String[] { certificatePw });
            params.put("androidKeystorePw", new String[] { keystorePw });
        }

        //Windows Phone
        if (mobilePlatform instanceof WindowsPhoneKeyProvider) {
            WindowsPhoneKeyProvider windowsPhone = (WindowsPhoneKeyProvider) mobilePlatform;

            String title = windowsPhone.getWinphonePublisherIdTitle();

            if (title.equals("")) {
                title = EnginePropertiesManager
                        .getProperty(PropertyName.MOBILE_BUILDER_WINDOWSPHONE_PUBLISHER_ID_TITLE);
            }

            params.put("winphonePublisherIdTitle", new String[] { title });
        }

        // Launch the mobile build
        URL url = new URL(mobileBuilderPlatformURL + "/build?" + URLUtils.mapToQuery(params));

        HostConfiguration hostConfiguration = new HostConfiguration();
        hostConfiguration.setHost(url.getHost());
        HttpState httpState = new HttpState();
        Engine.theApp.proxyManager.setProxy(hostConfiguration, httpState, url);

        PostMethod method = new PostMethod(url.toString());

        FileRequestEntity entity = new FileRequestEntity(mobileArchiveFile, null);
        method.setRequestEntity(entity);

        int methodStatusCode = Engine.theApp.httpClient.executeMethod(hostConfiguration, method, httpState);
        String sResult = IOUtils.toString(method.getResponseBodyAsStream(), "UTF-8");

        if (methodStatusCode != HttpStatus.SC_OK) {
            throw new ServiceException(
                    "Unable to build application '" + finalApplicationName + "'.\n" + sResult);
        }

        JSONObject jsonObject = new JSONObject(sResult);
        Element statusElement = document.createElement("application");
        statusElement.setAttribute("id", jsonObject.getString("id"));
        document.getDocumentElement().appendChild(statusElement);
    }
}

From source file:edu.virginia.speclab.juxta.author.view.export.WebServiceClient.java

/**
 * Send a cancel request to the webservice to abort the current
 * export operation.//from  w w w.j  a  v a 2 s.  co m
 * @throws IOException 
 */
public void cancelExport(String taskId) throws IOException {
    PostMethod post = new PostMethod(this.baseUrl + "/import/" + taskId + "/cancel");
    Part[] parts = { new StringPart("token", this.authToken) };
    post.setRequestEntity(new MultipartRequestEntity(parts, post.getParams()));
    execRequest(post);
    post.releaseConnection();
}

From source file:com.duowan.common.rpc.client.CommonsHttpInvokerRequestExecutor.java

/**
 * Set the given serialized remote invocation as request body.
 * <p>The default implementation simply sets the serialized invocation
 * as the PostMethod's request body. This can be overridden, for example,
 * to write a specific encoding and potentially set appropriate HTTP
 * request headers./*from w  w  w .  j a  v a 2  s  . c o  m*/
 * @param config the HTTP invoker configuration that specifies the target service
 * @param postMethod the PostMethod to set the request body on
 * @param baos the ByteArrayOutputStream that contains the serialized
 * RemoteInvocation object
 * @throws IOException if thrown by I/O methods
 * @see org.apache.commons.httpclient.methods.PostMethod#setRequestBody(java.io.InputStream)
 * @see org.apache.commons.httpclient.methods.PostMethod#setRequestEntity
 * @see org.apache.commons.httpclient.methods.InputStreamRequestEntity
 */
protected void setRequestBody(PostMethod postMethod, byte[] parameters) throws IOException {
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    outputStream.write(parameters);
    outputStream.close();
    postMethod.setRequestEntity(new ByteArrayRequestEntity(outputStream.toByteArray(), getContentType()));
}

From source file:com.pocketsoap.salesforce.soap.ChatterClient.java

private <T> T makeSoapRequest(String serverUrl, RequestEntity req, ResponseParser<T> respParser)
        throws XMLStreamException, IOException {
    PostMethod post = new PostMethod(serverUrl);
    post.addRequestHeader("SOAPAction", "\"\"");
    post.setRequestEntity(req);

    HttpClient http = new HttpClient();
    int sc = http.executeMethod(post);
    if (sc != 200 && sc != 500)
        throw new IOException("request to " + serverUrl + " returned unexpected HTTP status code of " + sc
                + ", check configuration.");

    XMLInputFactory f = XMLInputFactory.newInstance();
    f.setProperty(XMLInputFactory.IS_COALESCING, Boolean.TRUE);

    XMLStreamReader rdr = f.createXMLStreamReader(post.getResponseBodyAsStream());
    rdr.require(XMLStreamReader.START_DOCUMENT, null, null);
    rdr.nextTag();//from  ww  w .  j  a  va  2s .com
    rdr.require(XMLStreamReader.START_ELEMENT, SOAP_NS, "Envelope");
    rdr.nextTag();
    // TODO, should handle a Header appearing in the response.
    rdr.require(XMLStreamReader.START_ELEMENT, SOAP_NS, "Body");
    rdr.nextTag();
    if (rdr.getLocalName().equals("Fault")) {
        throw handleSoapFault(rdr);
    }
    try {
        T response = respParser.parse(rdr);
        while (rdr.hasNext())
            rdr.next();
        return response;
    } finally {
        try {
            rdr.close();
        } finally {
            post.releaseConnection();
        }
    }
}

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

public void deploy(String pathToTest, ProcessUnderTest put) throws DeploymentException {
    LOGGER.info("ODE deployer got request to deploy " + put);

    check(fArchive, "Archive Location");
    check(fDeploymentAdminServiceURL, "deployment admin server URL");

    String archivePath = getArchiveLocation(pathToTest);
    if (!new File(archivePath).exists()) {
        throw new DeploymentException(String.format("The archive location '%s' does not exist", archivePath));
    }// w  ww.  j  a  v a  2  s  .  c  o  m

    boolean archiveIsTemporary = false;
    if (!FilenameUtils.getName(archivePath).endsWith(".zip")) {
        // if the deployment is a directory and not a zip file
        if (new File(archivePath).isDirectory()) {
            archivePath = zipDirectory(new File(archivePath));

            // Separate zip file was created and should be later cleaned up
            archiveIsTemporary = true;
        } else {
            throw new DeploymentException("Unknown archive format for the archive " + fArchive);
        }
    }
    java.io.File uploadingFile = new java.io.File(archivePath);

    // process the bundle for replacing wsdl eprs here. requires base url
    // string from specification loader.
    // should be done via the ODEDeploymentArchiveHandler. hard coded ode
    // process deployment string will be used
    // to construct the epr of the process wsdl. this requires the location
    // of put wsdl in order to obtain the
    // service name of the process in process wsdl. alternatively can use
    // inputs from deploymentsoptions.

    // test coverage logic. Moved to ProcessUnderTest deploy() method.

    HttpClient client = new HttpClient(new NoPersistenceConnectionManager());
    PostMethod method = new PostMethod(fDeploymentAdminServiceURL);
    RequestEntity re = fFactory.getDeployRequestEntity(uploadingFile);
    method.setRequestEntity(re);

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

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

    String responseBody;
    int statusCode = 0;
    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 (uploadingFile.exists() && archiveIsTemporary) {
            uploadingFile.delete();
        }
    }

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

    try {
        fProcessId = extractProcessId(responseBody);
    } catch (IOException e) {
        throw new DeploymentException("Problem extracting deployment information: " + e.getMessage(), e);
    }
}

From source file:net.jadler.JadlerMockingIntegrationTest.java

@Test
public void havingParameterPOST() throws Exception {
    final String body = "p1=p1v1&p2=p2v1&p2=p2v2&p3=&p4&url%20encoded=url%20encoded";

    final PostMethod method = new PostMethod("http://localhost:" + port() + "?p2=p2v3");
    method.setRequestEntity(new StringRequestEntity(body, "application/x-www-form-urlencoded", "UTF-8"));

    client.executeMethod(method);//from w w w . j  a  v  a  2s  .c  om

    verifyThatRequest().havingParameter("p1").havingParameter("p1", hasSize(1))
            .havingParameter("p1", everyItem(not(isEmptyOrNullString())))
            .havingParameter("p1", contains("p1v1")).havingParameterEqualTo("p1", "p1v1").havingParameter("p2")
            .havingParameter("p2", hasSize(3)).havingParameter("p2", hasItems("p2v1", "p2v2", "p2v3"))
            .havingParameterEqualTo("p2", "p2v1").havingParameterEqualTo("p2", "p2v2")
            .havingParameterEqualTo("p2", "p2v3").havingParameters("p1", "p2").havingParameter("p3")
            .havingParameter("p3", contains("")).havingParameterEqualTo("p3", "").havingParameter("p4")
            .havingParameter("p4", contains("")).havingParameterEqualTo("p4", "")
            .havingParameter("p5", nullValue()).havingParameter("url%20encoded", contains("url%20encoded"))
            .havingBodyEqualTo(body).receivedOnce();
}

From source file:com.testmax.util.HttpUtil.java

public String postRequest(String url, String param, String xml) {

    String resp = "";

    PostMethod post = new PostMethod(url);

    if (param.equalsIgnoreCase("body")) {
        //xmlData=urlConf.getUrlParamValue(param);
        byte buf[] = xml.getBytes();
        ByteArrayInputStream in = new ByteArrayInputStream(buf);
        post.setRequestEntity(new InputStreamRequestEntity(new BufferedInputStream(in), xml.length()));

    } else {//from ww  w .j a va  2s  . c  o  m
        post.setRequestHeader(param, xml);
    }
    post.setRequestHeader("Content-type", "text/xml; charset=utf-8");
    // Get HTTP client
    org.apache.commons.httpclient.HttpClient httpsclient = new org.apache.commons.httpclient.HttpClient();

    // Execute request
    try {

        int response = -1;

        try {
            response = httpsclient.executeMethod(post);
            resp = post.getResponseBodyAsString();
            Header[] heads = post.getResponseHeaders();

            String header = "";
            for (Header head : heads) {
                header += head.getName() + ":" + head.getValue();
            }
            System.out.println("Header=" + header);
            WmLog.printMessage("Response: " + resp);
            WmLog.printMessage("Response Header: " + header);
        } catch (HttpException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    } finally {
        // Release current connection to the connection pool 
        // once you are done
        post.releaseConnection();
    }
    return resp;
}