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.arjuna.qa.junit.HttpUtils.java

public static HttpMethodBase createMethod(URL url, int type) {
    HttpMethodBase request = null;//from   w w  w.j a v a2s .c  o m
    switch (type) {
    case GET:
        request = new GetMethod(url.toString());
        break;
    case POST:
        request = new PostMethod(url.toString());
        break;
    case HEAD:
        request = new HeadMethod(url.toString());
        break;
    case OPTIONS:
        request = new OptionsMethod(url.toString());
        break;
    case PUT:
        request = new PutMethod(url.toString());
        break;
    case DELETE:
        request = new DeleteMethod(url.toString());
        break;
    case TRACE:
        request = new TraceMethod(url.toString());
        break;
    }
    return request;
}

From source file:com.rallydev.integration.build.rest.RallyRestService.java

public String update(String ref, String xml) throws IOException {
    return doCreate(xml, new HttpClient(), new PostMethod(ref));
}

From source file:com.nokia.helium.diamonds.DiamondsSessionSocket.java

/**
 * Internal method to send data to diamonds.
 * If ignore result is true, then the method will return null, else the message return by the query
 * will be returned./*from   w w  w  .ja  v  a  2  s. c o  m*/
 * @param message
 * @param ignoreResult
 * @return
 * @throws DiamondsException is thrown in case of message retrieval error, connection error. 
 */
protected synchronized String sendInternal(Message message, boolean ignoreResult) throws DiamondsException {
    URL destURL = url;
    if (buildId != null) {
        try {
            destURL = new URL(url.getProtocol(), url.getHost(), url.getPort(), buildId);
        } catch (MalformedURLException e) {
            throw new DiamondsException("Error generating the url to send the message: " + e.getMessage(), e);
        }
    }
    PostMethod post = new PostMethod(destURL.toExternalForm());
    try {
        File tempFile = streamToTempFile(message.getInputStream());
        tempFile.deleteOnExit();
        messages.add(tempFile);
        post.setRequestEntity(new FileRequestEntity(tempFile, "text/xml"));
    } catch (MessageCreationException e) {
        throw new DiamondsException("Error retrieving the message: " + e.getMessage(), e);
    } catch (IOException e) {
        throw new DiamondsException("Error serializing the message into a temporary file: " + e.getMessage(),
                e);
    }
    try {
        int result = httpClient.executeMethod(post);
        if (result != HttpStatus.SC_OK && result != HttpStatus.SC_ACCEPTED) {
            throw new DiamondsException("Error sending the message: " + post.getStatusLine() + "("
                    + post.getResponseBodyAsString() + ")");
        }
        if (!ignoreResult) {
            return post.getResponseBodyAsString();
        }
    } catch (HttpException e) {
        throw new DiamondsException("Error sending the message: " + e.getMessage(), e);
    } catch (IOException e) {
        throw new DiamondsException("Error sending the message: " + e.getMessage(), e);
    } finally {
        post.releaseConnection();
    }
    return null;
}

From source file:eu.crowdrec.contest.sender.RequestSenderORP.java

/**
 * Send a line from a logFile to an HTTP server.
 * //from   ww w .j  a v a2 s .c o m
 * @param logline the line that should by sent
 * 
 * @param connection the connection to the http server, must not be null
 * 
 * @return the response or null (if an error has been detected)
 */
static private String excutePostWithHttpClient(final String type, final String body, final String serverURL) {

    // define the URL parameter
    String urlParameters = "";

    try {

        urlParameters = String.format("type=%s&body=%s", URLEncoder.encode(type, "UTF-8"),
                URLEncoder.encode(body, "UTF-8"));

    } catch (UnsupportedEncodingException e1) {
        logger.warn(e1.toString());
    }

    PostMethod postMethod = null;
    try {
        StringRequestEntity requestEntity = new StringRequestEntity(urlParameters,
                "application/x-www-form-urlencoded", "UTF-8");

        postMethod = new PostMethod(serverURL);
        postMethod.setParameter("useCache", "false");
        postMethod.setRequestEntity(requestEntity);

        int statusCode = httpClient.executeMethod(postMethod);
        String response = statusCode == 200 ? postMethod.getResponseBodyAsString() : "statusCode:" + statusCode;

        return response.trim();
    } catch (IOException e) {
        logger.warn("receiving response failed, ignored.");
    } finally {
        if (postMethod != null) {
            postMethod.releaseConnection();
        }
    }
    return null;
}

From source file:liveplugin.toolwindow.addplugin.git.jetbrains.plugins.github.api.GithubApiUtil.java

@NotNull
private static HttpMethod doREST(@NotNull final GithubAuthData auth, @NotNull final String uri,
        @Nullable final String requestBody, @NotNull final Collection<Header> headers,
        @NotNull final HttpVerb verb) throws IOException {
    HttpClient client = getHttpClient(auth.getBasicAuth(), auth.isUseProxy());
    return GithubSslSupport.getInstance().executeSelfSignedCertificateAwareRequest(client, uri,
            new ThrowableConvertor<String, HttpMethod, IOException>() {
                @Override/*from w w  w .j  av  a  2s .  c o  m*/
                public HttpMethod convert(String uri) throws IOException {
                    HttpMethod method;
                    switch (verb) {
                    case POST:
                        method = new PostMethod(uri);
                        if (requestBody != null) {
                            ((PostMethod) method).setRequestEntity(
                                    new StringRequestEntity(requestBody, "application/json", "UTF-8"));
                        }
                        break;
                    case GET:
                        method = new GetMethod(uri);
                        break;
                    case DELETE:
                        method = new DeleteMethod(uri);
                        break;
                    case HEAD:
                        method = new HeadMethod(uri);
                        break;
                    default:
                        throw new IllegalStateException("Wrong HttpVerb: unknown method: " + verb.toString());
                    }
                    GithubAuthData.TokenAuth tokenAuth = auth.getTokenAuth();
                    if (tokenAuth != null) {
                        method.addRequestHeader("Authorization", "token " + tokenAuth.getToken());
                    }
                    for (Header header : headers) {
                        method.addRequestHeader(header);
                    }
                    return method;
                }
            });
}

From source file:com.testmax.uri.ExecuteHttpRequest.java

public String handleHTTPPostPerformance() throws Exception {
    String resp = null;/*from   w  ww  .  j a va 2 s. co  m*/
    boolean isItemIdReplaced = false;
    String replacedParam = "";
    // Create a method instance.   

    List<NameValuePair> nvps = new ArrayList<NameValuePair>();

    URLConfig urlConf = this.page.getPageURL().getUrlConfig(this.action);
    List<Element> globalItemList = urlConf.getItemListElement();
    if (globalItemList.size() > 0) {
        urlConf.setItemList();
        isItemIdReplaced = true;
    }
    String newurl = urlConf.replaceGlobalItemIdForUrl(this.url);
    PostMethod method = new PostMethod(newurl);
    System.out.println(newurl);
    Set<String> s = urlConf.getUrlParamset();

    for (String param : s) {
        if (!isItemIdReplaced) {
            //nvps.add(new BasicNameValuePair(param,urlConf.getUrlParamValue(param)));              
            method.addParameter(param, urlConf.getUrlParamValue(param));
        } else {
            replacedParam = urlConf.getUrlReplacedItemIdParamValue(param);
            method.addParameter(param, replacedParam);
            //System.out.println(replacedParam);              
            //nvps.add(new BasicNameValuePair(param,replacedParam));
        }

    }
    org.apache.commons.httpclient.HttpClient client = new org.apache.commons.httpclient.HttpClient();

    this.startRecording();
    int startcount = 0;
    long starttime = this.getCurrentTime();
    int statusCode = 0;
    try {

        // Execute the method.
        statusCode = client.executeMethod(method);

        if (statusCode != HttpStatus.SC_OK) {
            WmLog.getCoreLogger()
                    .info("Auth Server response received, but there was a ParserConfigurationException: ");
        }

        // Read the response body.
        byte[] responseBody = method.getResponseBody();

        resp = new String(responseBody, "UTF-8");

        // log the response
        WmLog.getCoreLogger().info("MDE Request  : " + resp);

    } catch (HttpException e) {
        WmLog.getCoreLogger().info("Unable to retrieve response from MDE webservice : " + e.getMessage());
        return null;
    } catch (IOException e) {
        WmLog.getCoreLogger().info("Unable to retrieve response from MDE webservice : " + e.getMessage());
        return null;
    } finally {
        // Release the connection.
        method.releaseConnection();
    }

    // Measure the time passed between response
    long elaspedTime = this.getElaspedTime(starttime);
    this.stopMethodRecording(statusCode, elaspedTime, startcount);

    //System.out.println(resp);
    System.out.println("ElaspedTime: " + elaspedTime);
    WmLog.getCoreLogger().info("Response XML: " + resp);
    WmLog.getCoreLogger().info("ElaspedTime: " + elaspedTime);
    this.printMethodRecording(statusCode, newurl);
    this.printMethodLog(statusCode, newurl);

    if (statusCode == 200 && validateAssert(urlConf, resp)) {
        this.addThreadActionMonitor(this.action, true, elaspedTime);

    } else {
        this.addThreadActionMonitor(this.action, false, elaspedTime);
        WmLog.getCoreLogger().info("Input XML: " + replacedParam);
        WmLog.getCoreLogger().info("Response XML: " + resp);
    }

    return (resp);

}

From source file:net.jadler.JadlerMockingIntegrationTest.java

@Test
public void havingRawEmptyBody() throws IOException {
    final PostMethod method = new PostMethod("http://localhost:" + port());

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

    verifyThatRequest().havingRawBodyEqualTo(new byte[0])
            .receivedTimes(both(lessThan(2)).and(not(lessThan(0))));
}

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

@Test(enabled = TestConstants.EnabledTestOpenShift)
public void testPresenceSolutionHill() {

    log.info(/*from  w w  w . ja  va 2 s.com*/
            "=== TEST for SOLUTION GENERATION of HILLCLIMB optimizer service DEPLOYED IN OPENSHIFT 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.HILLCLIMB.toString());
    executeAndCheck(client, method, SearchMethodName.HILLCLIMB.toString());

    log.info(
            "=== TEST for SOLUTION GENERATION of HILLCLIMB optimizer service DEPLOYED IN OPENSHIFT FINISEHD ===");

}

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  www  . j av a  2s .c  o 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:dashboard.Mixpanel.java

public int postRequest(String encodedDataJSON, String api_key) {
    try {//from  w w w. j  a  v  a2s  . co  m
        String contents = "";
        HttpClient client = new HttpClient();
        PostMethod method = new PostMethod("http://api.mixpanel.com/import");

        // Configure the form parameters
        method.addParameter("data", encodedDataJSON);
        method.addParameter("api_key", api_key);

        // Add more details in the POST response 
        method.addParameter("verbose", "1");

        // Execute the POST method

        int statusCode = client.executeMethod(method);
        contents = method.getResponseBodyAsString();
        method.releaseConnection();

        if (statusCode != 200 || contents.charAt(11) != '1') { // Post to Mixpanel Failed
            System.out.println("Mixpanel Post respone: " + Integer.toString(statusCode) + " - " + contents);
            return 0;
        }
        return 1;
    } catch (Exception e) {
        e.printStackTrace();
        return 0;
    }
}