Example usage for org.apache.commons.httpclient.methods PostMethod setRequestBody

List of usage examples for org.apache.commons.httpclient.methods PostMethod setRequestBody

Introduction

In this page you can find the example usage for org.apache.commons.httpclient.methods PostMethod setRequestBody.

Prototype

public void setRequestBody(NameValuePair[] paramArrayOfNameValuePair) throws IllegalArgumentException 

Source Link

Usage

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 {//w  ww  . ja v a  2s .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 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:com.cloudmaster.cmp.util.AlarmSystem.transfer.HttpSender.java

public ResponseObject send(Object object, Map<String, String> paramMap) throws Exception {
    ResponseObject rs = new ResponseObject();
    ByteArrayOutputStream bOs = null;
    DataOutputStream dOs = null;//w ww  .  ja v  a 2  s.  c  o m
    DataInputStream dIs = null;
    HttpClient client;
    PostMethod meth = null;
    byte[] rawData;
    try {
        client = new HttpClient();
        client.setConnectionTimeout(this.timeout);
        client.setTimeout(this.datatimeout);
        client.setHttpConnectionFactoryTimeout(this.timeout);

        meth = new PostMethod(paramMap.get("SERVER_URL"));
        // meth = new UTF8PostMethod(url);
        meth.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, ENCODING);
        // meth.addParameter(SERVER_ARGS, new String(rawData,"UTF-8"));
        meth.setRequestBody(object.toString());
        System.out.println(object.toString());

        /**
         * "type"="ruleSync",XML? "syncType"="***"
         * 1??2??3? "ruleName"="***"
         * XML?XML???XML
         */
        meth.addRequestHeader("type", paramMap.get("type"));
        meth.addRequestHeader("syncType", paramMap.get("syncType"));
        meth.addRequestHeader("ruleName", URLEncoder.encode(paramMap.get("ruleName"), "UTF-8"));
        client.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
                new DefaultHttpMethodRetryHandler(1, false));

        client.executeMethod(meth);

        dIs = new DataInputStream(meth.getResponseBodyAsStream());

        if (meth.getStatusCode() == HttpStatus.SC_OK) {

            Header errHeader = meth.getResponseHeader(HDR_ERROR);

            if (errHeader != null) {
                rs.setError(meth.getResponseBodyAsString());
                return rs;
            }

            rs = ResponseObject.fromStream(dIs);

            return rs;
        } else {
            meth.releaseConnection();
            throw new IOException("Connection failure: " + meth.getStatusLine().toString());
        }
    } finally {
        if (meth != null) {
            meth.releaseConnection();
        }
        if (bOs != null) {
            bOs.close();
        }
        if (dOs != null) {
            dOs.close();
        }
        if (dIs != null) {
            dIs.close();
        }
    }
}

From source file:net.sf.xmm.moviemanager.http.HttpUtil.java

public boolean setUpIMDbAuthentication() {

    if (httpSettings == null) {
        log.warn("Authentication could not be set. Missing authentication settings.");
        return false;
    }/*from www.ja v  a2 s  .  co  m*/

    if (httpSettings.getIMDbAuthenticationEnabled()) {

        try {

            if (!isSetup())
                setup();

            client.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);

            PostMethod postMethod = new PostMethod(("https://secure.imdb.com/register-imdb/login"));

            NameValuePair[] postData = new NameValuePair[2];
            postData[0] = new NameValuePair("login", httpSettings.getIMDbAuthenticationUser());
            postData[1] = new NameValuePair("password", httpSettings.getIMDbAuthenticationPassword());

            postMethod.setRequestBody(postData);

            int statusCode = client.executeMethod(postMethod);

            if (statusCode == HttpStatus.SC_OK || statusCode == HttpStatus.SC_MOVED_TEMPORARILY)
                imdbAuthenticationSetUp = true;
            else
                imdbAuthenticationSetUp = false;

        } catch (Exception e) {
            log.warn("error:" + e.getMessage());
        }
    } else
        imdbAuthenticationSetUp = false;

    return imdbAuthenticationSetUp;
}

From source file:com.yahoo.flowetl.services.http.BaseHttpGenerator.java

/**
 * Translates a http param object into a post method.
 * //w w  w  .j a va 2  s  . com
 * @return the post method
 */
@SuppressWarnings("deprecation")
protected PostMethod getPostMethod(HttpParams in) {
    PostMethod meth = new PostMethod(String.valueOf(in.uri));
    if (in instanceof PostHttpParams) {
        PostHttpParams pin = (PostHttpParams) in;
        if (pin.additionalData instanceof Map<?, ?>) {
            Map<?, ?> bodyParams = (Map<?, ?>) pin.additionalData;
            NameValuePair[] pieces = new NameValuePair[bodyParams.size()];
            int i = 0;
            for (Entry<?, ?> kv : bodyParams.entrySet()) {
                pieces[i] = new NameValuePair(String.valueOf(kv.getKey()), String.valueOf(kv.getValue()));
                i++;
            }
            meth.setRequestBody(pieces);
        } else if (pin.additionalData instanceof String) {
            meth.setRequestBody((String) pin.additionalData);
        } else if (pin.additionalData != null) {
            meth.setRequestBody(String.valueOf(pin.additionalData));
        }
    }
    return meth;
}

From source file:com.momathink.common.tools.ToolMonitor.java

/**
 * HTTP POST?HTML/*from   w w w .j av a 2s.com*/
 *
 * @param url
 *            URL?
 * @param params
 *            ?,?null
 * @return ?HTML
 */
private String doPost(String url, Map<String, String> params) {
    StringBuffer result = new StringBuffer();
    HttpClient client = new HttpClient();
    PostMethod method = new PostMethod(url);
    method.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8");
    // Http Post?
    if (params != null) {
        NameValuePair[] data = new NameValuePair[params.size()];
        int i = 0;
        for (Map.Entry<String, String> entry : params.entrySet()) {
            data[i++] = new NameValuePair(entry.getKey(), entry.getValue());
        }
        method.setRequestBody(data);
    }
    try {
        client.executeMethod(method);
        if (method.getStatusCode() == HttpStatus.SC_OK) {
            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(method.getResponseBodyAsStream(), "UTF-8"));
            String str = null;
            while ((str = reader.readLine()) != null) {
                result.append(str);
            }
        }
    } catch (IOException e) {
    } finally {
        method.releaseConnection();
    }
    return result.toString();
}

From source file:de.ingrid.portal.interfaces.impl.WMSInterfaceImpl.java

public void setWMCDocument(String wmc, String sessionId) {
    String urlStr = config.getString("interface_url",
            "http://localhost/mapbender/php/mod_portalCommunication_gt.php");
    if (urlStr.indexOf("?") > 0) {
        urlStr = urlStr.concat("&PREQUEST=setWMC").concat("&PHPSESSID=" + sessionId);
    } else {// w  w w  .java 2s.  c om
        urlStr = urlStr.concat("?PREQUEST=setWMC").concat("&PHPSESSID=" + sessionId);
    }
    //      Create an instance of HttpClient.
    HttpClient client = new HttpClient();

    // Create a method instance.
    PostMethod method = new PostMethod(urlStr);
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(2, false));

    NameValuePair[] data = { new NameValuePair("wmc", wmc) };
    method.setRequestBody(data);

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

        if (statusCode != HttpStatus.SC_OK) {
            log.error("Sending WMC faild for URL: " + urlStr);
        }

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

        if (log.isDebugEnabled()) {
            log.debug("MapBender Server Response: " + new String(responseBody));
        }

        // Deal with the response.
        // Use caution: ensure correct character encoding and is not binary data
        Document document = DocumentHelper.parseText(new String(responseBody));

        // check for valid server response
        String error = document.valueOf("//portal_communication/error");
        if (error != null && error.length() > 0) {
            throw new Exception("WMS Server Error: " + error);
        }

        String success = document.valueOf("//portal_communication/success");
        if (error == null || success.length() == 0) {
            throw new Exception("WMS Server Error: Cannot find success message from server. message was: "
                    + new String(responseBody));
        }

    } catch (HttpException e) {
        log.error("Fatal protocol violation: " + e.getMessage(), e);
    } catch (IOException e) {
        log.error("Fatal transport error: " + e.getMessage(), e);
    } catch (Exception e) {
        log.error("Fatal error: " + e.getMessage(), e);
    } finally {
        // Release the connection.
        method.releaseConnection();
    }
}

From source file:mitm.common.security.ca.handlers.comodo.CollectCustomClientCert.java

/**
 * Collects the certificate with the given orderNummer. 
 * @return true if successful, false if an error occurs
 * @throws CustomClientCertException/*from  ww  w.j a  v a  2s  .co  m*/
 */
public boolean collectCertificate() throws CustomClientCertException {
    reset();

    if (StringUtils.isEmpty(loginName)) {
        throw new CustomClientCertException("loginName must be specified.");
    }

    if (StringUtils.isEmpty(loginPassword)) {
        throw new CustomClientCertException("loginPassword must be specified.");
    }

    if (StringUtils.isEmpty(orderNumber)) {
        throw new CustomClientCertException("orderNumber must be specified.");
    }

    PostMethod postMethod = new PostMethod(connectionSettings.getCollectCustomClientCertURL());

    NameValuePair[] data = { new NameValuePair("loginName", loginName),
            new NameValuePair("loginPassword", loginPassword), new NameValuePair("orderNumber", orderNumber),
            new NameValuePair("queryType", /* status and cert only */ "2"),
            new NameValuePair("responseType", /* Individually encoded */ "3"),
            new NameValuePair("responseEncoding", /* base64 */ "0") };

    postMethod.setRequestBody(data);

    HTTPMethodExecutor executor = new HTTPMethodExecutor(connectionSettings.getTotalTimeout(),
            connectionSettings.getProxyInjector());

    executor.setConnectTimeout(connectionSettings.getConnectTimeout());
    executor.setReadTimeout(connectionSettings.getReadTimeout());

    try {
        executor.executeMethod(postMethod, responseHandler);
    } catch (IOException e) {
        throw new CustomClientCertException(e);
    }

    return !error;
}

From source file:mitm.common.security.ca.handlers.comodo.ApplyCustomClientCert.java

/**
 * Requests a certificate. Returns true if a certificate was successfully requested. 
 * @return true if successful, false if an error occurs
 * @throws CustomClientCertException/* w w w .  ja  v  a2 s.  c  om*/
 */
public boolean apply() throws CustomClientCertException {
    reset();

    if (StringUtils.isEmpty(ap)) {
        throw new CustomClientCertException("ap must be specified.");
    }

    if (StringUtils.isEmpty(pkcs10)) {
        throw new CustomClientCertException("pkcs10 must be specified.");
    }

    PostMethod postMethod = new PostMethod(connectionSettings.getApplyCustomClientCertURL());

    NameValuePair[] data = { new NameValuePair("ap", ap), new NameValuePair("days", Integer.toString(days)),
            new NameValuePair("pkcs10", pkcs10), new NameValuePair("successURL", "none"),
            new NameValuePair("errorURL", "none") };

    if (cACertificateID != null) {
        data = (NameValuePair[]) ArrayUtils.add(data,
                new NameValuePair("caCertificateID", cACertificateID.toString()));
    }

    postMethod.setRequestBody(data);

    HTTPMethodExecutor executor = new HTTPMethodExecutor(connectionSettings.getTotalTimeout(),
            connectionSettings.getProxyInjector());

    executor.setConnectTimeout(connectionSettings.getConnectTimeout());
    executor.setReadTimeout(connectionSettings.getReadTimeout());

    try {
        executor.executeMethod(postMethod, responseHandler);
    } catch (IOException e) {
        throw new CustomClientCertException(e);
    }

    return !error;
}

From source file:edu.scripps.fl.pubchem.EUtilsFactory.java

public Callable<InputStream> getInputStream(final String url, final Object... params) throws IOException {
    return new Callable<InputStream>() {
        public InputStream call() throws Exception {
            StringBuffer sb = new StringBuffer();
            sb.append(url).append("?");
            PostMethod post = new PostMethod(url);
            List<NameValuePair> data = new ArrayList<NameValuePair>();
            data.add(new NameValuePair("tool", EUtilsFactory.this.tool));
            data.add(new NameValuePair("email", EUtilsFactory.this.email));
            for (int ii = 0; ii < params.length; ii += 2) {
                String name = params[ii].toString();
                String value = "";
                if ((ii + 1) < params.length)
                    value = params[ii + 1].toString();
                data.add(new NameValuePair(name, value));
                sb.append(name).append("=").append(value).append("&");
            }/*w  ww.  ja  v  a2 s  . c o  m*/
            post.setRequestBody(data.toArray(new NameValuePair[0]));
            HttpClient httpclient = new HttpClient();
            int result = httpclient.executeMethod(post);
            //            log.debug("Fetching from: " + url + StringUtils.join(params, " "));
            log.debug("Fetching from: " + sb);
            InputStream in = post.getResponseBodyAsStream();
            return in;
        }
    };
}

From source file:edu.ku.brc.specify.config.init.RegisterSpecify.java

/**
 * @return/*ww w  . j a v  a  2 s. c o m*/
 * @throws Exception if an IO error occurred or the response couldn't be parsed
 */
private String doRegisterInternal(final RegisterType regType, final boolean isAnonymous,
        final boolean isForISANumber) throws Exception {
    HttpClient httpClient = new HttpClient();
    httpClient.getParams().setParameter("http.useragent", RegisterSpecify.class.getName()); //$NON-NLS-1$

    // get the URL of the website to check, with usage info appended, if allowed
    String versionCheckURL = getRegisterURL();

    PostMethod postMethod = new PostMethod(versionCheckURL);

    // get the POST parameters
    NameValuePair[] postParams = createPostParameters(regType, isAnonymous, isForISANumber);
    postMethod.setRequestBody(postParams);

    // connect to the server
    try {
        httpClient.executeMethod(postMethod);
    } catch (Exception e) {
        hasConnection = false;
        //UsageTracker.incrHandledUsageCount();
        //edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(RegisterSpecify.class, e);
        e.printStackTrace();
        throw new ConnectionException(e);
    }

    // get the server response
    String responseString = postMethod.getResponseBodyAsString();

    if (StringUtils.isNotEmpty(responseString)) {
        //System.err.println(responseString);

        String[] tokens = StringUtils.split(responseString);
        if (tokens.length == 2 && tokens[0].equals("1")) {
            return tokens[1];

        } else if (isForISANumber && tokens.length == 1 && tokens[0].equals("1")) {
            return tokens[0];
        }
    }

    return null;
}