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.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:com.intuit.tank.http.multipart.MultiPartRequest.java

/**
 * Execute the POST./*  w  w w .j av  a  2 s  .c  om*/
 */
public void doPost(BaseResponse response) {
    PostMethod httppost = null;
    String theUrl = null;
    try {
        URL url = BaseRequestHandler.buildUrl(protocol, host, port, path, urlVariables);
        theUrl = url.toExternalForm();
        httppost = new PostMethod(url.toString());
        String requestBody = getBody();

        List<Part> parts = buildParts();

        httppost.setRequestEntity(
                new MultipartRequestEntity(parts.toArray(new Part[parts.size()]), httppost.getParams()));

        sendRequest(response, httppost, requestBody);
    } catch (MalformedURLException e) {
        LOG.error(LogUtil.getLogMessage("Malformed URL Exception: " + e.toString(), LogEventType.IO), e);
        // swallowing error. validatin will check if there is no response
        // and take appropriate action
        throw new RuntimeException(e);
    } catch (Exception ex) {
        // logger.error(LogUtil.getLogMessage(ex.toString()), ex);
        // swallowing error. validatin will check if there is no response
        // and take appropriate action
        throw new RuntimeException(ex);
    } finally {
        if (null != httppost) {
            httppost.releaseConnection();
        }
        if (APITestHarness.getInstance().getTankConfig().getAgentConfig().getLogPostResponse()) {
            LOG.info(
                    LogUtil.getLogMessage(
                            "Response from POST to " + theUrl + " got status code " + response.getHttpCode()
                                    + " BODY { " + response.getResponseBody() + " }",
                            LogEventType.Informational));
        }
    }

}

From source file:com.cloud.baremetal.networkservice.SecurityGroupHttpClient.java

public HashMap<String, Pair<Long, Long>> sync(String vmName, Long vmId, String agentIp) {
    HashMap<String, Pair<Long, Long>> states = new HashMap<String, Pair<Long, Long>>();
    PostMethod post = new PostMethod(String.format("http://%s:%s/", agentIp, getPort()));
    try {/*from   ww  w  .j  a va 2s  . c  o m*/
        post.addRequestHeader("command", "sync");
        if (httpClient.executeMethod(post) != 200) {
            logger.debug(String.format("echoing baremetal security group agent on %s got error: %s", agentIp,
                    post.getResponseBodyAsString()));
        } else {
            String res = post.getResponseBodyAsString();
            // res = ';'.join([vmName, vmId, seqno])
            String[] rulelogs = res.split(",");
            if (rulelogs.length != 6) {
                logger.debug(
                        String.format("host[%s] returns invalid security group sync document[%s], reset rules",
                                agentIp, res));
                states.put(vmName, new Pair<Long, Long>(vmId, -1L));
                return states;
            }
            Pair<Long, Long> p = new Pair<Long, Long>(Long.valueOf(rulelogs[1]), Long.valueOf(rulelogs[5]));
            states.put(rulelogs[0], p);
            return states;
        }
    } catch (SocketTimeoutException se) {
        logger.warn(
                String.format("unable to sync security group rules on host[%s], %s", agentIp, se.getMessage()));
    } catch (Exception e) {
        logger.warn(String.format("unable to sync security group rules on host[%s]", agentIp), e);
    } finally {
        if (post != null) {
            post.releaseConnection();
        }
    }
    return states;
}

From source file:ch.flatland.cdo.client.internal.http.HTTPSClientConnector.java

protected PostMethod createHTTPMethod(String url) {
    return new PostMethod(url);
}

From source file:fr.opensagres.xdocreport.remoting.converter.server.ConverterServiceTestCase.java

@Test
public void convertPDF() throws Exception {

    PostMethod post = new PostMethod("http://localhost:" + PORT + "/convert");

    String ct = "multipart/mixed";
    post.setRequestHeader("Content-Type", ct);
    Part[] parts = new Part[4];
    String fileName = "ODTCV.odt";

    parts[0] = new FilePart("document", new File(root, fileName), "application/vnd.oasis.opendocument.text",
            "UTF-8");
    parts[1] = new StringPart("outputFormat", ConverterTypeTo.PDF.name());
    parts[2] = new StringPart("via", ConverterTypeVia.ODFDOM.name());
    parts[3] = new StringPart("download", "true");
    post.setRequestEntity(new MultipartRequestEntity(parts, post.getParams()));

    HttpClient httpclient = new HttpClient();

    try {//from   w w  w . ja v a2 s.  co m
        int result = httpclient.executeMethod(post);
        Assert.assertEquals(200, result);
        Assert.assertEquals("attachment; filename=\"ODTCV_odt.pdf\"",
                post.getResponseHeader("Content-Disposition").getValue());

        byte[] convertedDocument = post.getResponseBody();
        Assert.assertNotNull(convertedDocument);

        File outFile = new File("target/ODTCV_odt.pdf");
        outFile.getParentFile().mkdirs();
        IOUtils.copy(new ByteArrayInputStream(convertedDocument), new FileOutputStream(outFile));

    } finally {

        post.releaseConnection();
    }
}

From source file:com.synox.android.operations.OAuth2GetAccessToken.java

@Override
protected RemoteOperationResult run(OwnCloudClient client) {
    RemoteOperationResult result = null;
    PostMethod postMethod = null;// w w w  . j  av a 2s.co m

    try {
        parseAuthorizationResponse();
        if (mOAuth2ParsedAuthorizationResponse.keySet().contains(OAuth2Constants.KEY_ERROR)) {
            if (OAuth2Constants.VALUE_ERROR_ACCESS_DENIED
                    .equals(mOAuth2ParsedAuthorizationResponse.get(OAuth2Constants.KEY_ERROR))) {
                result = new RemoteOperationResult(ResultCode.OAUTH2_ERROR_ACCESS_DENIED);
            } else {
                result = new RemoteOperationResult(ResultCode.OAUTH2_ERROR);
            }
        }

        if (result == null) {
            NameValuePair[] nameValuePairs = new NameValuePair[4];
            nameValuePairs[0] = new NameValuePair(OAuth2Constants.KEY_GRANT_TYPE, mGrantType);
            nameValuePairs[1] = new NameValuePair(OAuth2Constants.KEY_CODE,
                    mOAuth2ParsedAuthorizationResponse.get(OAuth2Constants.KEY_CODE));
            nameValuePairs[2] = new NameValuePair(OAuth2Constants.KEY_REDIRECT_URI, mRedirectUri);
            nameValuePairs[3] = new NameValuePair(OAuth2Constants.KEY_CLIENT_ID, mClientId);
            //nameValuePairs[4] = new NameValuePair(OAuth2Constants.KEY_SCOPE, mOAuth2ParsedAuthorizationResponse.get(OAuth2Constants.KEY_SCOPE));         

            postMethod = new PostMethod(client.getWebdavUri().toString());
            postMethod.setRequestBody(nameValuePairs);
            int status = client.executeMethod(postMethod);

            String response = postMethod.getResponseBodyAsString();
            if (response != null && response.length() > 0) {
                JSONObject tokenJson = new JSONObject(response);
                parseAccessTokenResult(tokenJson);
                if (mResultTokenMap.get(OAuth2Constants.KEY_ERROR) != null
                        || mResultTokenMap.get(OAuth2Constants.KEY_ACCESS_TOKEN) == null) {
                    result = new RemoteOperationResult(ResultCode.OAUTH2_ERROR);

                } else {
                    result = new RemoteOperationResult(true, status, postMethod.getResponseHeaders());
                    ArrayList<Object> data = new ArrayList<>();
                    data.add(mResultTokenMap);
                    result.setData(data);
                }

            } else {
                client.exhaustResponse(postMethod.getResponseBodyAsStream());
                result = new RemoteOperationResult(false, status, postMethod.getResponseHeaders());
            }
        }

    } catch (Exception e) {
        result = new RemoteOperationResult(e);

    } finally {
        if (postMethod != null)
            postMethod.releaseConnection(); // let the connection available for other methods

        if (result.isSuccess()) {
            Log_OC.i(TAG,
                    "OAuth2 TOKEN REQUEST with auth code " + mOAuth2ParsedAuthorizationResponse.get("code")
                            + " to " + client.getWebdavUri() + ": " + result.getLogMessage());

        } else if (result.getException() != null) {
            Log_OC.e(TAG,
                    "OAuth2 TOKEN REQUEST with auth code " + mOAuth2ParsedAuthorizationResponse.get("code")
                            + " to " + client.getWebdavUri() + ": " + result.getLogMessage(),
                    result.getException());

        } else if (result.getCode() == ResultCode.OAUTH2_ERROR) {
            Log_OC.e(TAG, "OAuth2 TOKEN REQUEST with auth code "
                    + mOAuth2ParsedAuthorizationResponse.get("code") + " to " + client.getWebdavUri() + ": "
                    + ((mResultTokenMap != null) ? mResultTokenMap.get(OAuth2Constants.KEY_ERROR) : "NULL"));

        } else {
            Log_OC.e(TAG,
                    "OAuth2 TOKEN REQUEST with auth code " + mOAuth2ParsedAuthorizationResponse.get("code")
                            + " to " + client.getWebdavUri() + ": " + result.getLogMessage());
        }
    }

    return result;
}

From source file:fr.cls.atoll.motu.library.misc.cas.TestCASRest.java

public static Cookie[] validateFromCAS2(String username, String password) throws Exception {

    String url = casServerUrlPrefix + "/v1/tickets?";

    String s = URLEncoder.encode("username", "UTF-8") + "=" + URLEncoder.encode(username, "UTF-8");
    s += "&" + URLEncoder.encode("password", "UTF-8") + "=" + URLEncoder.encode(password, "UTF-8");

    HttpState initialState = new HttpState();
    // Initial set of cookies can be retrieved from persistent storage and
    // re-created, using a persistence mechanism of choice,
    // Cookie mycookie = new Cookie(".foobar.com", "mycookie", "stuff", "/", null, false);

    // Create an instance of HttpClient.
    // HttpClient client = new HttpClient();
    HttpClient client = new HttpClient();

    Protocol easyhttps = new Protocol("https", new EasySSLProtocolSocketFactory(), 8443);

    URI uri = new URI(url + s, true);
    // use relative url only
    PostMethod httpget = new PostMethod(url);
    httpget.addParameter("username", username);
    httpget.addParameter("password", password);

    HostConfiguration hc = new HostConfiguration();
    hc.setHost("atoll-dev.cls.fr", 8443, easyhttps);
    // client.executeMethod(hc, httpget);

    client.setState(initialState);//from w  ww .j a  va 2  s .c  om

    // Create a method instance.
    System.out.println(url + s);

    GetMethod method = new GetMethod(url + s);
    // GetMethod method = new GetMethod(url );

    HostConfiguration hostConfiguration = new HostConfiguration();
    hostConfiguration.setProxy("proxy.cls.fr", 8080);
    client.setHostConfiguration(hostConfiguration);

    // Provide custom retry handler is necessary
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(3, false));
    // String username = "xxx";
    // String password = "xxx";
    // Credentials credentials = new UsernamePasswordCredentials(username, password);
    // AuthScope authScope = new AuthScope("proxy.cls.fr", 8080);
    //           
    // client.getState().setProxyCredentials(authScope, credentials);
    Cookie[] cookies = null;

    try {
        // Execute the method.
        // int statusCode = client.executeMethod(method);
        int statusCode = client.executeMethod(hc, httpget);

        if (statusCode != HttpStatus.SC_OK) {
            System.err.println("Method failed: " + method.getStatusLine());
        }

        for (Header header : method.getRequestHeaders()) {
            System.out.println(header.getName());
            System.out.println(header.getValue());
        }
        // Read the response body.
        byte[] responseBody = method.getResponseBody();

        // Deal with the response.
        // Use caution: ensure correct character encoding and is not binary data
        System.out.println(new String(responseBody));

        System.out.println("Response status code: " + statusCode);
        // Get all the cookies
        cookies = client.getState().getCookies();
        // Display the cookies
        System.out.println("Present cookies: ");
        for (int i = 0; i < cookies.length; i++) {
            System.out.println(" - " + cookies[i].toExternalForm());
        }

        Assertion assertion = AssertionHolder.getAssertion();
        if (assertion == null) {
            System.out.println("<p>Assertion is null</p>");
        }

    } catch (HttpException e) {
        System.err.println("Fatal protocol violation: " + e.getMessage());
        e.printStackTrace();
    } catch (IOException e) {
        System.err.println("Fatal transport error: " + e.getMessage());
        e.printStackTrace();
    } finally {
        // Release the connection.
        method.releaseConnection();
    }

    return cookies;

}

From source file:com.cerema.cloud2.operations.OAuth2GetAccessToken.java

@Override
protected RemoteOperationResult run(OwnCloudClient client) {
    RemoteOperationResult result = null;
    PostMethod postMethod = null;// ww  w  . ja v  a  2s  .  co  m

    try {
        parseAuthorizationResponse();
        if (mOAuth2ParsedAuthorizationResponse.keySet().contains(OAuth2Constants.KEY_ERROR)) {
            if (OAuth2Constants.VALUE_ERROR_ACCESS_DENIED
                    .equals(mOAuth2ParsedAuthorizationResponse.get(OAuth2Constants.KEY_ERROR))) {
                result = new RemoteOperationResult(ResultCode.OAUTH2_ERROR_ACCESS_DENIED);
            } else {
                result = new RemoteOperationResult(ResultCode.OAUTH2_ERROR);
            }
        }

        if (result == null) {
            NameValuePair[] nameValuePairs = new NameValuePair[4];
            nameValuePairs[0] = new NameValuePair(OAuth2Constants.KEY_GRANT_TYPE, mGrantType);
            nameValuePairs[1] = new NameValuePair(OAuth2Constants.KEY_CODE,
                    mOAuth2ParsedAuthorizationResponse.get(OAuth2Constants.KEY_CODE));
            nameValuePairs[2] = new NameValuePair(OAuth2Constants.KEY_REDIRECT_URI, mRedirectUri);
            nameValuePairs[3] = new NameValuePair(OAuth2Constants.KEY_CLIENT_ID, mClientId);
            //nameValuePairs[4] = new NameValuePair(OAuth2Constants.KEY_SCOPE, mOAuth2ParsedAuthorizationResponse.get(OAuth2Constants.KEY_SCOPE));         

            postMethod = new PostMethod(client.getWebdavUri().toString());
            postMethod.setRequestBody(nameValuePairs);
            int status = client.executeMethod(postMethod);

            String response = postMethod.getResponseBodyAsString();
            if (response != null && response.length() > 0) {
                JSONObject tokenJson = new JSONObject(response);
                parseAccessTokenResult(tokenJson);
                if (mResultTokenMap.get(OAuth2Constants.KEY_ERROR) != null
                        || mResultTokenMap.get(OAuth2Constants.KEY_ACCESS_TOKEN) == null) {
                    result = new RemoteOperationResult(ResultCode.OAUTH2_ERROR);

                } else {
                    result = new RemoteOperationResult(true, status, postMethod.getResponseHeaders());
                    ArrayList<Object> data = new ArrayList<Object>();
                    data.add(mResultTokenMap);
                    result.setData(data);
                }

            } else {
                client.exhaustResponse(postMethod.getResponseBodyAsStream());
                result = new RemoteOperationResult(false, status, postMethod.getResponseHeaders());
            }
        }

    } catch (Exception e) {
        result = new RemoteOperationResult(e);

    } finally {
        if (postMethod != null)
            postMethod.releaseConnection(); // let the connection available for other methods

        if (result.isSuccess()) {
            Log_OC.i(TAG,
                    "OAuth2 TOKEN REQUEST with auth code " + mOAuth2ParsedAuthorizationResponse.get("code")
                            + " to " + client.getWebdavUri() + ": " + result.getLogMessage());

        } else if (result.getException() != null) {
            Log_OC.e(TAG,
                    "OAuth2 TOKEN REQUEST with auth code " + mOAuth2ParsedAuthorizationResponse.get("code")
                            + " to " + client.getWebdavUri() + ": " + result.getLogMessage(),
                    result.getException());

        } else if (result.getCode() == ResultCode.OAUTH2_ERROR) {
            Log_OC.e(TAG, "OAuth2 TOKEN REQUEST with auth code "
                    + mOAuth2ParsedAuthorizationResponse.get("code") + " to " + client.getWebdavUri() + ": "
                    + ((mResultTokenMap != null) ? mResultTokenMap.get(OAuth2Constants.KEY_ERROR) : "NULL"));

        } else {
            Log_OC.e(TAG,
                    "OAuth2 TOKEN REQUEST with auth code " + mOAuth2ParsedAuthorizationResponse.get("code")
                            + " to " + client.getWebdavUri() + ": " + result.getLogMessage());
        }
    }

    return result;
}

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

@Override
protected void writeResponseResult(HttpServletRequest request, HttpServletResponse response) throws Exception {
    String project = Keys.project.value(request);

    MobileApplication mobileApplication = GetBuildStatus.getMobileApplication(project);

    if (mobileApplication == null) {
        throw new ServiceException("no such mobile application");
    } else {//from w  ww. j  a v a 2s. 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!");
        }
    }

    String platformName = Keys.platform.value(request);
    String finalApplicationName = mobileApplication.getComputedApplicationName();

    String mobileBuilderPlatformURL = EnginePropertiesManager
            .getProperty(PropertyName.MOBILE_BUILDER_PLATFORM_URL);

    PostMethod method;
    int methodStatusCode;
    InputStream methodBodyContentInputStream;

    URL url = new URL(mobileBuilderPlatformURL + "/getpackage");

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

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

    try {
        HeaderName.ContentType.setRequestHeader(method, MimeType.WwwForm.value());
        method.setRequestBody(new NameValuePair[] { new NameValuePair("application", finalApplicationName),
                new NameValuePair("platformName", platformName),
                new NameValuePair("auth_token", mobileApplication.getComputedAuthenticationToken()),
                new NameValuePair("endpoint", mobileApplication.getComputedEndpoint(request)) });

        methodStatusCode = Engine.theApp.httpClient.executeMethod(hostConfiguration, method, httpState);
        methodBodyContentInputStream = method.getResponseBodyAsStream();

        if (methodStatusCode != HttpStatus.SC_OK) {
            byte[] httpBytes = IOUtils.toByteArray(methodBodyContentInputStream);
            String sResult = new String(httpBytes, "UTF-8");
            throw new ServiceException("Unable to get package for project '" + project + "' (final app name: '"
                    + finalApplicationName + "').\n" + sResult);
        }

        try {
            String contentDisposition = method.getResponseHeader(HeaderName.ContentDisposition.value())
                    .getValue();
            HeaderName.ContentDisposition.setHeader(response, contentDisposition);
        } catch (Exception e) {
            HeaderName.ContentDisposition.setHeader(response, "attachment; filename=\"" + project + "\"");
        }

        try {
            response.setContentType(method.getResponseHeader(HeaderName.ContentType.value()).getValue());
        } catch (Exception e) {
            response.setContentType(MimeType.OctetStream.value());
        }

        OutputStream responseOutputStream = response.getOutputStream();
        IOUtils.copy(methodBodyContentInputStream, responseOutputStream);
    } catch (IOException ioex) { // Fix for ticket #4698
        if (!ioex.getClass().getSimpleName().equalsIgnoreCase("ClientAbortException")) {
            // fix for #5042
            throw ioex;
        }
    } finally {
        method.releaseConnection();
    }
}

From source file:net.jadler.JadlerMockingIntegrationTest.java

@Test
public void havingRawBody() throws IOException {
    final PostMethod method = new PostMethod("http://localhost:" + port());
    method.setRequestEntity(new ByteArrayRequestEntity(BINARY_BODY));

    client.executeMethod(method);/*from   ww  w . j av  a2  s  . co m*/

    verifyThatRequest().havingRawBodyEqualTo(BINARY_BODY).receivedTimes(equalTo(1));
}