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.griddynamics.jagger.coordinator.http.client.ExchangeClient.java

private String exchangeData(String url, Serializable obj) throws IOException {
    PostMethod method = new PostMethod(urlBase + url);
    NameValuePair pair = new NameValuePair();
    pair.setName(MESSAGE);/* ww  w  .j av a 2s. c om*/
    pair.setValue(SerializationUtils.toString(obj));

    method.setQueryString(new NameValuePair[] { pair });
    try {
        int returnCode = httpClient.executeMethod(method);
        log.debug("Exchange response code {}", returnCode);
        return method.getResponseBodyAsString();
    } finally {
        try {
            method.releaseConnection();
        } catch (Throwable e) {
            log.error("Cannot release connection", e);
        }
    }
}

From source file:net.morphbank.webclient.ProcessFiles.java

public InputStream post(String strURL, String strXMLFilename, PrintWriter out) throws Exception {
    InputStream response = null;/*from  w w  w.j  av  a2s  . c o  m*/
    File input = new File(strXMLFilename);
    // Prepare HTTP post
    PostMethod post = new PostMethod(strURL);
    // Request content will be retrieved directly
    // from the input stream Part[] parts = {
    Part[] parts = { new FilePart("uploadFile", strXMLFilename, input) };
    RequestEntity entity = new MultipartRequestEntity(parts, post.getParams());
    // RequestEntity entity = new FileRequestEntity(input,
    // "text/xml;charset=utf-8");
    post.setRequestEntity(entity);
    // Get HTTP client
    HttpClient httpclient = new HttpClient();
    // Execute request
    try {
        int result = httpclient.executeMethod(post);
        // Display status code
        System.out.println("Response status code: " + result);
        // Display response
        response = post.getResponseBodyAsStream();
        for (int i = response.read(); i != -1; i = response.read()) {
            out.write(i);
        }
    } finally {
        // Release current connection to the connection pool once you are
        // done
        post.releaseConnection();
    }
    return response;
}

From source file:fedora.test.integration.TestLargeDatastreams.java

private String upload() throws Exception {
    String url = fedoraClient.getUploadURL();
    EntityEnclosingMethod httpMethod = new PostMethod(url);
    httpMethod.setDoAuthentication(true);
    httpMethod.getParams().setParameter("Connection", "Keep-Alive");
    httpMethod.setContentChunked(true);/*from   ww w .ja va 2s.c  om*/
    Part[] parts = { new FilePart("file", new SizedPartSource()) };
    httpMethod.setRequestEntity(new MultipartRequestEntity(parts, httpMethod.getParams()));
    HttpClient client = fedoraClient.getHttpClient();
    try {

        int status = client.executeMethod(httpMethod);
        String response = new String(httpMethod.getResponseBody());

        if (status != HttpStatus.SC_CREATED) {
            throw new IOException("Upload failed: " + HttpStatus.getStatusText(status) + ": "
                    + replaceNewlines(response, " "));
        } else {
            response = response.replaceAll("\r", "").replaceAll("\n", "");
            return response;
        }
    } finally {
        httpMethod.releaseConnection();
    }
}

From source file:com.owncloud.android.lib.resources.shares.CreateRemoteShareOperation.java

@Override
protected RemoteOperationResult run(OwnCloudClient client) {
    RemoteOperationResult result = null;
    int status = -1;

    PostMethod post = null;/*from   w ww.ja  v a2s  .  c  o m*/

    try {
        // Post Method
        post = new PostMethod(client.getBaseUri() + ShareUtils.SHARING_API_PATH);
        //Log_OC.d(TAG, "URL ------> " + client.getBaseUri() + ShareUtils.SHARING_API_PATH);

        post.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8"); // necessary for special characters
        post.addParameter(PARAM_PATH, mRemoteFilePath);
        post.addParameter(PARAM_SHARE_TYPE, Integer.toString(mShareType.getValue()));
        post.addParameter(PARAM_SHARE_WITH, mShareWith);
        post.addParameter(PARAM_PUBLIC_UPLOAD, Boolean.toString(mPublicUpload));
        if (mPassword != null && mPassword.length() > 0) {
            post.addParameter(PARAM_PASSWORD, mPassword);
        }
        post.addParameter(PARAM_PERMISSIONS, Integer.toString(mPermissions));

        post.addRequestHeader(OCS_API_HEADER, OCS_API_HEADER_VALUE);

        status = client.executeMethod(post);

        if (isSuccess(status)) {
            String response = post.getResponseBodyAsString();

            result = new RemoteOperationResult(ResultCode.OK);

            // Parse xml response --> obtain the response in ShareFiles ArrayList
            // convert String into InputStream
            InputStream is = new ByteArrayInputStream(response.getBytes());
            ShareXMLParser xmlParser = new ShareXMLParser();
            mShares = xmlParser.parseXMLResponse(is);
            if (xmlParser.isSuccess()) {
                if (mShares != null) {
                    Log_OC.d(TAG, "Created " + mShares.size() + " share(s)");
                    result = new RemoteOperationResult(ResultCode.OK);
                    ArrayList<Object> sharesObjects = new ArrayList<Object>();
                    for (OCShare share : mShares) {
                        sharesObjects.add(share);
                    }
                    result.setData(sharesObjects);
                }
            } else if (xmlParser.isFileNotFound()) {
                result = new RemoteOperationResult(ResultCode.SHARE_NOT_FOUND);

            } else if (xmlParser.isFailure()) {
                result = new RemoteOperationResult(ResultCode.SHARE_FORBIDDEN);

            } else {
                result = new RemoteOperationResult(false, status, post.getResponseHeaders());
            }

        } else {
            result = new RemoteOperationResult(false, status, post.getResponseHeaders());
        }

    } catch (Exception e) {
        result = new RemoteOperationResult(e);
        Log_OC.e(TAG, "Exception while Creating New Share", e);

    } finally {
        if (post != null) {
            post.releaseConnection();
        }
    }
    return result;
}

From source file:jails.http.client.CommonsClientHttpRequestFactory.java

/**
 * Create a Commons HttpMethodBase object for the given HTTP method
 * and URI specification.//  w ww. ja  v a2  s.  c  o  m
 * @param httpMethod the HTTP method
 * @param uri the URI
 * @return the Commons HttpMethodBase object
 */
protected HttpMethodBase createCommonsHttpMethod(HttpMethod httpMethod, String uri) {
    switch (httpMethod) {
    case GET:
        return new GetMethod(uri);
    case DELETE:
        return new DeleteMethod(uri);
    case HEAD:
        return new HeadMethod(uri);
    case OPTIONS:
        return new OptionsMethod(uri);
    case POST:
        return new PostMethod(uri);
    case PUT:
        return new PutMethod(uri);
    case TRACE:
        return new TraceMethod(uri);
    default:
        throw new IllegalArgumentException("Invalid HTTP method: " + httpMethod);
    }
}

From source file:net.jadler.JadlerMockingIntegrationTest.java

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

    client.executeMethod(method);

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

From source file:com.zimbra.examples.extns.samlprovider.SamlAuthProvider.java

/**
 * Returns an AuthToken by auth data in SOAP request.
 * <p/>// ww  w .j  av a2s . c om
 * Should never return null.
 *
 * @param soapCtxt soap context element
 * @param engineCtxt soap engine context
 * @return auth token
 * @throws AuthTokenException if auth data for the provider is not present
 * @throws AuthProviderException if auth data for the provider is present but cannot be resolved into a valid AuthToken
 */
protected AuthToken authToken(Element soapCtxt, Map engineCtxt)
        throws AuthProviderException, AuthTokenException {

    if (soapCtxt == null)
        throw AuthProviderException.NO_AUTH_DATA();

    Element authTokenElt;
    String type;
    try {
        authTokenElt = soapCtxt.getElement("authToken");
        if (authTokenElt == null)
            throw AuthProviderException.NO_AUTH_DATA();
        type = authTokenElt.getAttribute("type");
    } catch (AuthProviderException ape) {
        throw ape;
    } catch (ServiceException se) {
        ZimbraLog.extensions.error(SystemUtil.getStackTrace(se));
        throw AuthProviderException.NO_AUTH_DATA();
    }
    if (!"SAML_AUTH_PROVIDER".equals(type)) {
        throw AuthProviderException.NOT_SUPPORTED();
    }

    String samlAssertionId = authTokenElt.getTextTrim();
    if (samlAssertionId == null || "".equals(samlAssertionId))
        throw AuthProviderException.NO_AUTH_DATA();

    String samlAuthorityUrl = LC.get("saml_authority_url");
    if (samlAuthorityUrl == null)
        throw new AuthTokenException("SAML authority URL has not been specified in localconfig.zml");

    HttpClient client = new HttpClient();
    PostMethod post = new PostMethod(samlAuthorityUrl);
    Element samlAssertionReq = getSamlAssertionRequest(samlAssertionId);
    String samlAssertionReqStr = samlAssertionReq.toString();
    if (ZimbraLog.extensions.isDebugEnabled()) {
        ZimbraLog.extensions.debug("SAML assertion request: " + samlAssertionReqStr);
    }
    try {
        post.setRequestEntity(new StringRequestEntity(samlAssertionReqStr, "text/xml", "utf-8"));
        client.executeMethod(post);
        Element samlResp = Element.parseXML(post.getResponseBodyAsStream());
        Element soapBody = samlResp.getElement("Body");
        Element responseElt = soapBody.getElement("Response");
        Element samlAssertionElt = responseElt.getElement("Assertion");
        if (samlAssertionElt == null) {
            throw new AuthTokenException("SAML response does not contain a SAML token");
        }
        return new SamlAuthToken(samlAssertionElt);
    } catch (AuthTokenException ate) {
        throw ate;
    } catch (Exception e) {
        ZimbraLog.extensions.error(SystemUtil.getStackTrace(e));
        throw new AuthTokenException("Exception in executing SAML assertion request", e);
    }
}

From source file:eu.seaclouds.platform.planner.optimizerTest.service.OptimizerServiceTestIT.java

@Test(enabled = TestConstants.EnabledTest)
public void testPresenceSolutionAnneal() {

    log.info("=== TEST for SOLUTION GENERATION of ANNEAL optimizer service STARTED ===");

    String url = BASE_URL + "optimize";

    HttpClient client = new HttpClient();
    PostMethod method = new PostMethod(url);

    method.addParameter("aam", appModel);
    method.addParameter("offers", suitableCloudOffer);
    method.addParameter("optmethod", SearchMethodName.ANNEAL.toString());

    executeAndCheck(client, method);/*w  ww  .jav  a2s .c o m*/

    log.info("=== TEST for SOLUTION GENERATION of ANNEAL optimizer service FINISEHD ===");

}

From source file:eu.learnpad.core.impl.sim.XwikiBridgeInterfaceRestResource.java

@Override
public Collection<String> addProcessDefinition(String processDefinitionFileURL, String modelSetId)
        throws LpRestException {
    HttpClient httpClient = this.getAnonymousClient();
    String uri;/*from   w  w  w . j a va2s .  c  o  m*/
    if (modelSetId != null) {
        uri = String.format("%s/learnpad/sim/bridge/processes?modelsetartifactid=%s", this.restPrefix,
                modelSetId);
    } else {
        uri = String.format("%s/learnpad/sim/bridge/processes", this.restPrefix);
    }

    PostMethod postMethod = new PostMethod(uri);
    postMethod.addRequestHeader("Content-Type", "application/json");

    try {
        RequestEntity requestEntity = new StringRequestEntity(processDefinitionFileURL, "application/json",
                "UTF-8");
        postMethod.setRequestEntity(requestEntity);

        httpClient.executeMethod(postMethod);

        // Not fully tested, but is looks working for our purposes -- Gulyx
        return this.objectReaderCollection.readValue(postMethod.getResponseBodyAsStream());
    } catch (IOException e) {
        throw new LpRestExceptionXWikiImpl(e.getMessage(), e.getCause());
    }
}

From source file:com.legstar.test.cixs.AbstractHttpClientTester.java

/**
 * Perform a request/reply using text/xml as payload.
 * /*from  w  ww .  ja  v  a2s . com*/
 * @param url the target url
 * @param xmlRequest the XML request
 * @param soapAction the soap action
 * @return the XML reply
 * @throws Exception if something goes wrong
 */
public String postXml(final String url, final String xmlRequest, final String soapAction) throws Exception {
    PostMethod postMethod = new PostMethod(url);
    if (soapAction != null && soapAction.length() > 0) {
        postMethod.setRequestHeader("SOAPAction", soapAction);
    }
    StringRequestEntity requestEntity = new StringRequestEntity(xmlRequest, "text/xml", "utf-8");
    postMethod.setRequestEntity(requestEntity);
    int rc = HTTPCLIENT.executeMethod(postMethod);
    String xmlReply = getResponseBodyAsString(postMethod.getResponseBodyAsStream(),
            postMethod.getResponseCharSet());
    postMethod.releaseConnection();
    assertEquals(postMethod.getStatusText() + " " + xmlReply, 200, rc);
    return xmlReply;
}