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.twinsoft.convertigo.engine.billing.GoogleAnalyticsTicketManager.java

public synchronized void addTicket(Ticket ticket) throws BillingException {
    if (log.isDebugEnabled()) {
        log.debug("(GoogleAnalyticsTicketManager) addTicket " + ticket);
    }//w  w w .j  av  a  2 s.  c  o m
    PostMethod method = new PostMethod(urls[0]);
    HeaderName.ContentType.setRequestHeader(method, MimeType.WwwForm.value());

    // set parameters for POST method
    method.setParameter("v", "1");
    method.setParameter("tid", analyticsID);

    String cid = ticket.getDeviceUUID();
    if (cid.isEmpty()) {
        cid = ticket.getSessionID();
    }
    try {
        cid = UuidUtils.toUUID(cid).toString();
    } catch (Exception e) {
        log.debug("(GoogleAnalyticsTicketManager) failed to get DeviceUUID", e);
    }

    method.setParameter("cid", cid);
    method.setParameter("uid", ticket.getUserName());
    method.setParameter("uip", ticket.getClientIp());

    method.setParameter("t", "event");
    method.setParameter("an", ticket.getProjectName());
    method.setParameter("ec", ticket.getProjectName());

    StringBuffer requestableName = new StringBuffer(ticket.getConnectorName());
    if (requestableName.length() > 0) {
        requestableName.append('.');
    }
    method.setParameter("ea", requestableName.append(ticket.getRequestableName()).toString());
    method.setParameter("ev", Long.toString(ticket.getResponseTime()));
    method.setParameter("ua", ticket.getUserAgent());

    // execute HTTP post with parameters
    if (GAClient != null) {
        try {
            int httpCode = GAClient.executeMethod(method);
            String body = method.getResponseBodyAsString();
            log.debug("[" + httpCode + "] " + body);
        } catch (MalformedURLException e) {
            log.error("(GoogleAnalyticsTicketManager) error creating GAanalytics HttpClient, bad url", e);
        } catch (HttpException e) {
            log.error(
                    "(GoogleAnalyticsTicketManager) error creating GAanalytics HttpClient, Error in HTTP request",
                    e);
        } catch (IOException e) {
            log.error("(GoogleAnalyticsTicketManager) error creating GAanalytics HttpClient, I/O error", e);
        }
    }
}

From source file:com._17od.upm.transport.HTTPTransport.java

public void put(String targetLocation, File file, String username, String password) throws TransportException {

    targetLocation = addTrailingSlash(targetLocation) + "upload.php";

    PostMethod post = new PostMethod(targetLocation);

    //This part is wrapped in a try/finally so that we can ensure
    //the connection to the HTTP server is always closed cleanly 
    try {//  w ww . j  a v a2  s  .com

        Part[] parts = { new FilePart("userfile", file) };
        post.setRequestEntity(new MultipartRequestEntity(parts, post.getParams()));

        //Set the HTTP authentication details
        if (username != null) {
            Credentials creds = new UsernamePasswordCredentials(new String(username), new String(password));
            URL url = new URL(targetLocation);
            AuthScope authScope = new AuthScope(url.getHost(), url.getPort());
            client.getState().setCredentials(authScope, creds);
            client.getParams().setAuthenticationPreemptive(true);
        }

        // This line makes the HTTP call
        int status = client.executeMethod(post);

        // I've noticed on Windows (at least) that PHP seems to fail when moving files on the first attempt
        // The second attempt works so lets just do that
        if (status == HttpStatus.SC_OK && post.getResponseBodyAsString().equals("FILE_WASNT_MOVED")) {
            status = client.executeMethod(post);
        }

        if (status != HttpStatus.SC_OK) {
            throw new TransportException(
                    "There's been some kind of problem uploading a file to the HTTP server.\n\nThe HTTP error message is ["
                            + HttpStatus.getStatusText(status) + "]");
        }

        if (!post.getResponseBodyAsString().equals("OK")) {
            throw new TransportException(
                    "There's been some kind of problem uploading a file to the HTTP server.\n\nThe error message is ["
                            + post.getResponseBodyAsString() + "]");
        }

    } catch (FileNotFoundException e) {
        throw new TransportException(e);
    } catch (MalformedURLException e) {
        throw new TransportException(e);
    } catch (HttpException e) {
        throw new TransportException(e);
    } catch (IOException e) {
        throw new TransportException(e);
    } finally {
        post.releaseConnection();
    }

}

From source file:net.jadler.JadlerStubbingIntegrationTest.java

@Test
public void havingBody() throws Exception {
    onRequest().havingBodyEqualTo("postbody").havingBody(notNullValue()).havingBody(not(isEmptyOrNullString()))
            .respond().withStatus(201);//from w w  w .  ja va 2s  .  co m

    final PostMethod method = new PostMethod("http://localhost:" + port());
    method.setRequestEntity(new StringRequestEntity("postbody", null, null));

    int status = client.executeMethod(method);
    assertThat(status, is(201));
}

From source file:fr.unix_experience.owncloud_sms.engine.OCHttpClient.java

PostMethod pushSms(StringRequestEntity ent) {
    PostMethod post = new PostMethod(_serverURI.toString() + OCHttpClient.OC_PUSH_ROUTE);
    post.setRequestEntity(ent);
    return post;
}

From source file:com.funambol.json.dao.AuthenticatorDAOImpl.java

public JsonResponse login(String jsonObject) throws HttpException, IOException {

    String request = Utility.getUrl(serverUrl, LOGIN_URL);

    if (log.isTraceEnabled()) {
        log.trace("Login Request: " + request);
    }//from  ww w .j a v a2  s .  com

    PostMethod post = new PostMethod(request);
    post.setRequestEntity(new StringRequestEntity(jsonObject));

    int statusCode = 0;
    String responseBody = null;
    try {
        statusCode = httpClient.executeMethod(post);
        responseBody = post.getResponseBodyAsString();
    } finally {
        post.releaseConnection();
    }

    if (log.isTraceEnabled()) {
        log.trace("---------> statusCode: " + statusCode + " responseBody: " + responseBody);
    }

    JsonResponse jsonServerResponse = new JsonResponse(statusCode, responseBody);
    return jsonServerResponse;
}

From source file:com.shelrick.openamplify.client.OpenAmplifyClientImpl.java

@Override
public OpenAmplifyResponse searchText(String inputText, Analysis analysis, List<String> searchTermsList,
        Integer maxTopicResults) throws OpenAmplifyClientException {
    List<NameValuePair> params = getBaseParams();
    params.add(new NameValuePair("inputtext", inputText));
    params.add(new NameValuePair("analysis", analysis.type()));
    params.add(new NameValuePair("searchTerms", getSearchTerms(searchTermsList)));
    params.add(new NameValuePair("maxtopicresult", maxTopicResults.toString()));

    PostMethod postMethod = new PostMethod(apiUrl);
    postMethod.addParameters(params.toArray(new NameValuePair[1]));

    String responseText = doRequest(postMethod);
    return parseResponse(responseText, analysis);
}

From source file:hydrograph.ui.communication.debugservice.method.Provider.java

/**
 * /*w  w w . ja v a 2  s .com*/
 * Get post method to get csv debug file
 * 
 * @param jobDetails
 * @param fileSize
 * @return {@link PostMethod}
 * @throws NumberFormatException
 * @throws MalformedURLException
 */
public PostMethod getDebugFileMethod(JobDetails jobDetails, String fileSize)
        throws NumberFormatException, MalformedURLException {

    URL url = new URL(POST_PROTOCOL, getHost(jobDetails), getPortNo(jobDetails),
            DebugServiceMethods.GET_DEBUG_FILE_PATH);

    PostMethod postMethod = new PostMethod(url.toString());
    postMethod.addParameter(DebugServicePostParameters.JOB_ID, jobDetails.getUniqueJobID());
    postMethod.addParameter(DebugServicePostParameters.COMPONENT_ID, jobDetails.getComponentID());
    postMethod.addParameter(DebugServicePostParameters.SOCKET_ID, jobDetails.getComponentSocketID());
    postMethod.addParameter(DebugServicePostParameters.BASE_PATH, jobDetails.getBasepath());
    postMethod.addParameter(DebugServicePostParameters.USER_ID, jobDetails.getUsername());
    postMethod.addParameter(DebugServicePostParameters.DEBUG_SERVICE_PWD, jobDetails.getPassword());
    postMethod.addParameter(DebugServicePostParameters.FILE_SIZE, fileSize);
    postMethod.addParameter(DebugServicePostParameters.HOST_NAME, getHost(jobDetails));

    LOGGER.debug("Calling debug service to get csv debug file from url :: " + url);

    return postMethod;
}

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

/** 
 * [@EVENT] This method is invoked when the sender is required to 
 * create a HTTP Request from configuration.
 * <br/><br/>//ww w  . j a  v  a  2 s  . co m
 * By default, this method return a PostMethod pointing to {@link #getServiceEndPoint()}.    
 * 
 * @throws Exception 
 *          Sub-class implementation-specific exception
 */
protected HttpMethod onCreateRequest() throws Exception {
    return new PostMethod(this.serviceEndPoint.toExternalForm());
}

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));
    }/*from   ww  w .j a va2  s .  co  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:com.cloud.utils.rest.RESTValidationStrategy.java

/**
 * Logs against the REST server. The cookie is stored in the <code>_authcookie<code> variable.
 * <p>//from w ww . j a v a2  s  .  c o m
 * The method returns false if the login failed or the connection could not be made.
 *
 */
protected void login(final String protocol, final HttpClient client) throws CloudstackRESTException {
    String url;

    if (host == null || host.isEmpty() || user == null || user.isEmpty() || password == null
            || password.isEmpty()) {
        throw new CloudstackRESTException("Hostname/credentials are null or empty");
    }

    try {
        url = new URL(protocol, host, loginUrl).toString();
    } catch (final MalformedURLException e) {
        s_logger.error("Unable to build Nicira API URL", e);
        throw new CloudstackRESTException("Unable to build Nicira API URL", e);
    }

    final PostMethod pm = new PostMethod(url);
    pm.addParameter("username", user);
    pm.addParameter("password", password);

    try {
        client.executeMethod(pm);
    } catch (final HttpException e) {
        throw new CloudstackRESTException("REST Service API login failed ", e);
    } catch (final IOException e) {
        throw new CloudstackRESTException("REST Service API login failed ", e);
    } finally {
        pm.releaseConnection();
    }

    if (pm.getStatusCode() != HttpStatus.SC_OK) {
        s_logger.error("REST Service API login failed : " + pm.getStatusText());
        throw new CloudstackRESTException("REST Service API login failed " + pm.getStatusText());
    }

    // Extract the version for later use
    if (pm.getResponseHeader("Server") != null) {
        serverVersion = pm.getResponseHeader("Server").getValue();
        s_logger.debug("Server reports version " + serverVersion);
    }

    // Success; the cookie required for login is kept in _client
}