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.pureinfo.force.net.impl.HttpUtilImpl.java

/**
 * @see com.pureinfo.force.net.IHttpUtil#getContent(String, NameValuePair[],
 *      String, String)//w w  w.ja  va2s .  c  o  m
 */
public String getContent(String _sUrl, NameValuePair[] _args, String _sRequestCharset, String _sResponseCharset)
        throws IOTransferException {
    if (_sRequestCharset == null) {
        _sRequestCharset = "utf-8";
    }

    //1. to create http client and set proxy
    HttpClient client = new HttpClient();
    if (m_proxyHost != null) {
        client.getHostConfiguration().setProxyHost(m_proxyHost);
        if (m_sProxyUser != null & m_sProxyPassword != null) {
            client.getState().setProxyCredentials(//
                    new AuthScope(m_proxyHost.getHostName(), m_proxyHost.getPort()),
                    new UsernamePasswordCredentials(m_sProxyUser, m_sProxyPassword));
        }
    }

    //2. to create post
    PostMethod method = new PostMethod(_sUrl);
    if (m_nRetryCount > 0) {
        method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, //
                new DefaultHttpMethodRetryHandler(m_nRetryCount, false));
    }
    method.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=" + _sRequestCharset);
    for (int i = 0; _args != null && i < _args.length; i++) {
        method.addParameter(_args[i]);
    }

    //3. to send request and read response
    String sResponse;
    try {
        client.executeMethod(method);
        sResponse = method.getResponseBodyAsString();
        if (!method.getRequestCharSet().equals(_sRequestCharset)) {
            sResponse = new String(sResponse.getBytes(), _sResponseCharset);
        }
        return sResponse;
    } catch (Exception ex) {
        throw new IOTransferException(_sUrl, ex);
    } finally {
        method.releaseConnection();
    }
}

From source file:au.org.ala.cas.client.WebServiceAuthenticationHelper.java

/**
 * Authenticates user credentials with CAS server and obtains a Ticket Granting ticket.
 * /*from  w ww.j a  v  a2 s.  co  m*/
 * @param server   CAS server URI
 * @param username User name
 * @param password Password
 * @return The Ticket Granting Ticket id
 */
private String getTicketGrantingTicket(final String server, final String username, final String password) {
    final HttpClient client = new HttpClient();

    final PostMethod post = new PostMethod(server + CAS_CONTEXT);

    post.setRequestBody(new NameValuePair[] { new NameValuePair("username", username),
            new NameValuePair("password", password) });

    try {
        client.executeMethod(post);

        final String response = post.getResponseBodyAsString();

        switch (post.getStatusCode()) {
        case 201: {
            final Matcher matcher = Pattern.compile(".*action=\".*/(.*?)\".*").matcher(response);

            if (matcher.matches())
                return matcher.group(1);

            logger.warn("Successful ticket granting request, but no ticket found!");
            logger.info("Response (1k): " + getMaxString(response));
            break;
        }

        default:
            logger.warn("Invalid response code (" + post.getStatusCode() + ") from CAS server!");
            logger.info("Response (1k): " + getMaxString(response));
            break;
        }
    }

    catch (final IOException e) {
        logger.warn(e.getMessage(), e);
    }

    finally {
        post.releaseConnection();
    }

    return null;
}

From source file:ccc.api.http.SiteBrowserImpl.java

/** {@inheritDoc} */
@Override/*from  w  w w.j  a v  a  2  s  .c  o m*/
public String postUrlEncoded(final ResourceSummary rs, final Map<String, String[]> params) {
    /* This method deliberately elides charset values to replicate the
     * behaviour of a typical browser.                                    */

    final PostMethod post = new PostMethod(_hostUrl + rs.getAbsolutePath());
    post.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

    final List<NameValuePair> qParams = new ArrayList<NameValuePair>();
    for (final Map.Entry<String, String[]> param : params.entrySet()) {
        for (final String value : param.getValue()) {
            final NameValuePair qParam = new NameValuePair(param.getKey(), value);
            qParams.add(qParam);
        }
    }

    final StringBuilder buffer = createQueryString(qParams);
    post.setRequestEntity(new StringRequestEntity(buffer.toString()));

    return invoke(post);
}

From source file:com.moss.jaxwslite.Service.java

public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

    if (args == null) {
        args = new Object[0];
    }//from www  . j  a v  a2  s .c  o m

    if (method.getName().equals("toString") && args.length == 0) {
        return url.toString();
    }

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

    final byte[] requestContent = type.request(method, args);

    RequestEntity requestEntity = new ByteArrayRequestEntity(requestContent);
    post.setRequestEntity(requestEntity);
    post.addRequestHeader("Content-Type", "text/xml");

    if (log.isDebugEnabled()) {
        new Thread() {
            public void run() {
                try {
                    setPriority(MIN_PRIORITY);

                    ByteArrayOutputStream out = new ByteArrayOutputStream();
                    JAXBHelper.beautify(new ByteArrayInputStream(requestContent), out);

                    StringBuilder sb = new StringBuilder();
                    sb.append("Sending post: ").append(url).append("\n");
                    sb.append(new String(out.toByteArray()));

                    log.debug(sb.toString());
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }
        }.start();
    }

    try {

        int responseCode = client.executeMethod(post);
        boolean fault = responseCode != 200;

        final byte[] responseContent;
        {
            InputStream in = post.getResponseBodyAsStream();
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024 * 10]; //10k buffer
            for (int numRead = in.read(buffer); numRead != -1; numRead = in.read(buffer)) {
                out.write(buffer, 0, numRead);
            }
            responseContent = out.toByteArray();
        }

        if (log.isDebugEnabled()) {
            new Thread() {
                public void run() {
                    try {
                        setPriority(MIN_PRIORITY);

                        ByteArrayOutputStream out = new ByteArrayOutputStream();
                        JAXBHelper.beautify(new ByteArrayInputStream(responseContent), out);

                        StringBuilder sb = new StringBuilder();
                        sb.append("Receiving post response: ").append(url).append("\n");
                        sb.append(new String(out.toByteArray()));

                        log.debug(sb.toString());
                    } catch (Exception e) {
                        throw new RuntimeException(e);
                    }
                }
            }.start();
        }

        Object response = type.response(method, responseContent, fault);

        if (response instanceof Exception) {
            throw (Exception) response;
        } else {
            return response;
        }
    } finally {
        post.releaseConnection();
    }
}

From source file:edu.wfu.inotado.helper.RestClientHelper.java

/**
 * Calculate a signature using the given key and the xml.
 * /* www  . ja v a 2  s. c om*/
 * Add the calculated signature into header.
 * 
 * @param strURL
 * @param xml
 * @param key
 * @return
 */
public String postXml(String strURL, String xml, String key) {
    // create a new PostMethod and place it in the holder
    postHolder.set(new PostMethod(strURL));
    if (StringUtils.isNotEmpty(key)) {
        try {
            // add the calculated signature into header
            postHolder.get().addRequestHeader("Signature",
                    this.encryptionHelper.calculateHMAC(xml, this.encryptionHelper.key));
        } catch (SignatureException e) {
            log.error("Unable to generate sigature", e);
        }
    }
    return postXml(strURL, xml);
}

From source file:com.denimgroup.threadfix.remote.HttpRestUtils.java

@Nonnull
public <T> RestResponse<T> httpPostFile(@Nonnull String path, @Nonnull File file, @Nonnull String[] paramNames,
        @Nonnull String[] paramVals, @Nonnull Class<T> targetClass) {

    if (isUnsafeFlag())
        Protocol.registerProtocol("https", new Protocol("https", new AcceptAllTrustFactory(), 443));

    String completeUrl = makePostUrl(path);
    if (completeUrl == null) {
        LOGGER.debug("The POST url could not be generated. Aborting request.");
        return ResponseParser
                .getErrorResponse("The POST url could not be generated and the request was not attempted.", 0);
    }/*from w w w .ja v a  2 s.c om*/

    PostMethod filePost = new PostMethod(completeUrl);

    filePost.setRequestHeader("Accept", "application/json");

    RestResponse<T> response = null;
    int status = -1;

    try {
        Part[] parts = new Part[paramNames.length + 2];
        parts[paramNames.length] = new FilePart("file", file);
        parts[paramNames.length + 1] = new StringPart("apiKey", propertiesManager.getKey());

        for (int i = 0; i < paramNames.length; i++) {
            parts[i] = new StringPart(paramNames[i], paramVals[i]);
        }

        filePost.setRequestEntity(new MultipartRequestEntity(parts, filePost.getParams()));

        filePost.setContentChunked(true);
        HttpClient client = new HttpClient();
        status = client.executeMethod(filePost);

        if (status != 200) {
            LOGGER.warn("Request for '" + completeUrl + "' status was " + status + ", not 200 as expected.");
        }

        if (status == 302) {
            Header location = filePost.getResponseHeader("Location");
            printRedirectInformation(location);
        }

        response = ResponseParser.getRestResponse(filePost.getResponseBodyAsStream(), status, targetClass);

    } catch (SSLHandshakeException sslHandshakeException) {

        importCert(sslHandshakeException);

    } catch (IOException e1) {
        LOGGER.error("There was an error and the POST request was not finished.", e1);
        response = ResponseParser.getErrorResponse("There was an error and the POST request was not finished.",
                status);
    }

    return response;
}

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

@Override
protected void getServiceResult(HttpServletRequest request, Document document) throws Exception {
    String project = Keys.project.value(request);

    MobileApplication mobileApplication = getMobileApplication(project);

    if (mobileApplication == null) {
        throw new ServiceException("no such mobile application");
    } else {/*from  w ww.j a v  a 2 s  .c o  m*/
        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 mobileBuilderPlatformURL = EnginePropertiesManager
            .getProperty(PropertyName.MOBILE_BUILDER_PLATFORM_URL);

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

    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());

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

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

        InputStream methodBodyContentInputStream = method.getResponseBodyAsStream();
        byte[] httpBytes = IOUtils.toByteArray(methodBodyContentInputStream);
        String sResult = new String(httpBytes, "UTF-8");

        if (methodStatusCode != HttpStatus.SC_OK) {
            throw new ServiceException(
                    "Unable to get building status for application '" + project + "' (final app name: '"
                            + mobileApplication.getComputedApplicationName() + "').\n" + sResult);
        }

        jsonResult = new JSONObject(sResult);
    } finally {
        method.releaseConnection();
    }

    Element statusElement = document.createElement("build");
    statusElement.setAttribute(Keys.project.name(), project);
    statusElement.setAttribute(Keys.platform.name(), platformName);

    if (jsonResult.has(platformName + "_status")) {
        statusElement.setAttribute("status", jsonResult.getString(platformName + "_status"));
    } else {
        statusElement.setAttribute("status", "none");
    }

    if (jsonResult.has(platformName + "_error")) {
        statusElement.setAttribute("error", jsonResult.getString(platformName + "_error"));
    }

    statusElement.setAttribute("version", jsonResult.has("version") ? jsonResult.getString("version") : "n/a");
    statusElement.setAttribute("phonegap_version",
            jsonResult.has("phonegap_version") ? jsonResult.getString("phonegap_version") : "n/a");

    statusElement.setAttribute("revision",
            jsonResult.has("revision") ? jsonResult.getString("revision") : "n/a");
    statusElement.setAttribute("endpoint",
            jsonResult.has("endpoint") ? jsonResult.getString("endpoint") : "n/a");

    document.getDocumentElement().appendChild(statusElement);
}

From source file:edu.northwestern.bioinformatics.studycalendar.security.plugin.cas.direct.DirectLoginHttpFacade.java

protected PostMethod createLoginPostMethod() {
    PostMethod method = new PostMethod(getLoginUrl());
    method.setParameter("service", getServiceUrl());
    return initMethod(method);
}

From source file:com.honnix.cheater.network.CheaterHttpClient.java

public boolean login() {
    // Clear all exising cookies before logging in.
    httpClient.getState().clearCookies();

    PostMethod postMethod = new PostMethod(CheaterConstant.LOGIN_URL);

    postMethod.setParameter(CheaterConstant.USER_NAME_KEY, CheaterConstant.USER);
    postMethod.setParameter(CheaterConstant.PASSWORD_KEY, CheaterConstant.PASSWORD);
    postMethod.setParameter(CheaterConstant.TIMEZONE_OFFSET_KEY, CheaterConstant.TIMEZONE_OFFSET);
    postMethod.setParameter(CheaterConstant.REALM_KEY, CheaterConstant.REALM);

    boolean result = execute(postMethod);

    if (result) {
        for (Validator validator : validatorList) {
            result = validator.isLoginValid(httpClient, postMethod);
        }//  w  w w .j  av a  2s. c om
    }

    postMethod.releaseConnection();

    return result;
}

From source file:eu.learnpad.cw.rest.internal.DefaultXWikiPackage.java

private void postObject(File objectFile, String spaceName, String pageName, String className)
        throws XWikiRestException {
    HttpClient httpClient = new HttpClient();
    httpClient.getParams().setAuthenticationPreemptive(true);
    Credentials defaultcreds = new UsernamePasswordCredentials("Admin", "admin");
    httpClient.getState().setCredentials(new AuthScope("localhost", 8080, AuthScope.ANY_REALM), defaultcreds);

    PostMethod postMethod = new PostMethod("http://localhost:8080/xwiki/rest/wikis/xwiki/spaces/" + spaceName
            + "/pages/" + pageName + "/objects");
    postMethod.addRequestHeader("Accept", "application/xml");
    postMethod.addRequestHeader("Accept-Ranges", "bytes");
    RequestEntity fileRequestEntity = new FileRequestEntity(objectFile, "application/xml");
    postMethod.setRequestEntity(fileRequestEntity);
    try {// ww  w  .j  av a2s .  c  om
        httpClient.executeMethod(postMethod);
    } catch (HttpException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}