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:colt.nicity.performance.latent.http.ApacheHttpClient.java

public HttpResponse postJson(String path, String postJsonBody) {
    try {//  www  .j a  va 2 s  . c o  m
        PostMethod post = new PostMethod(path);
        post.setRequestEntity(new StringRequestEntity(postJsonBody, APPLICATION_JSON_CONTENT_TYPE, "UTF-8"));
        post.setRequestHeader(CONTENT_TYPE_HEADER_NAME, APPLICATION_JSON_CONTENT_TYPE);
        return execute(post);
    } catch (Exception e) {
        String trimmedPostBody = (postJsonBody.length() > JSON_POST_LOG_LENGTH_LIMIT)
                ? postJsonBody.substring(0, JSON_POST_LOG_LENGTH_LIMIT)
                : postJsonBody;
        throw new RuntimeException(
                "Error executing POST request to: " + client.getHostConfiguration().getHostURL() + " path: "
                        + path + " JSON body: " + trimmedPostBody,
                e);
    }
}

From source file:massbank.CallCgi.java

public void run() {
    String progName = "CallCgi";
    String msg = "";

    HttpClient client = new HttpClient();
    // ^CAEgl(msec)Zbg
    client.setTimeout(m_timeout * 1000);
    PostMethod method = new PostMethod(this.m_url);
    String strParam = "";
    if (m_params != null && m_params.size() > 0) {
        for (Enumeration keys = m_params.keys(); keys.hasMoreElements();) {
            String key = (String) keys.nextElement();
            if (!key.equals("inst_grp") && !key.equals("inst") && !key.equals("ms")
                    && !key.equals("inst_grp_adv") && !key.equals("inst_adv") && !key.equals("ms_adv")) {
                // L?[InstrumentType,MSTypeO??Stringp??[^
                String val = (String) m_params.get(key);
                strParam += key + "=" + val + "&";
                method.addParameter(key, val);
            } else {
                // L?[InstrumentType,MSType??Stringzp??[^
                String[] vals = (String[]) m_params.get(key);
                for (int i = 0; i < vals.length; i++) {
                    strParam += key + "=" + vals[i] + "&";
                    method.addParameter(key, vals[i]);
                }//from  ww w.  j  a  v a 2s  .  c  o  m
            }
        }
        strParam = strParam.substring(0, strParam.length() - 1);
    }

    try {
        // ?s
        int statusCode = client.executeMethod(method);
        // Xe?[^XR?[h`FbN
        if (statusCode != HttpStatus.SC_OK) {
            // G?[
            msg = method.getStatusLine().toString() + "\n" + "URL  : " + this.m_url;
            msg += "\nPARAM : " + strParam;
            MassBankLog.ErrorLog(progName, msg, m_context);
            return;
        }
        // X|X
        //         this.result = method.getResponseBodyAsString();

        /**
         * modification start
         * Use method.getResponseBodyAsStream() rather 
         * than method.getResponseBodyAsString() (marked as deprecated) for updated HttpClient library.
         * Prevents logging of message:
         * "Going to buffer response body of large or unknown size. Using getResponseBodyAsStream instead is recommended."
         */

        String charset = method.getResponseCharSet();
        InputStream is = method.getResponseBodyAsStream();
        StringBuilder sb = new StringBuilder();
        String line = "";
        if (is != null) {
            BufferedReader reader = new BufferedReader(new InputStreamReader(is, charset));
            while ((line = reader.readLine()) != null) {
                reader.mark(2000);
                String forward = reader.readLine();
                if ((line.equals("") || line.equals("\n") || line.equals("OK")) && forward == null)
                    sb.append(line); // append last line to StringBuilder
                else if (forward != null)
                    sb.append(line).append("\n"); // append current line with explicit line break
                else
                    sb.append(line);

                reader.reset();
            }
            reader.close();
            is.close();

            //            this.result = sb.toString().trim();
            this.result = sb.toString(); // trim() deleted. because the last [\t] and [\n] are removed.
            if (this.result.endsWith("\n")) // remove trailing line break
            {
                int pos = this.result.lastIndexOf("\n");
                this.result = this.result.substring(0, pos);
            }
        } else {
            this.result = "";
        }

        /**
         * modification end
         */
    } catch (Exception e) {
        // G?[
        msg = e.toString() + "\n" + "URL  : " + this.m_url;
        msg += "\nPARAM : " + strParam;
        MassBankLog.ErrorLog(progName, msg, m_context);
    } finally {
        // RlNV
        method.releaseConnection();
    }
}

From source file:de.softwareforge.pgpsigner.util.HKPSender.java

public boolean uploadKey(final byte[] armoredKey) {

    PostMethod post = new PostMethod(UPLOAD_URL);

    try {//from ww w  .j av  a2 s. c o m

        NameValuePair keyText = new NameValuePair("keytext", new String(armoredKey, "ISO-8859-1"));
        post.setRequestBody(new NameValuePair[] { keyText });
        post.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
                new DefaultHttpMethodRetryHandler(3, false));

        int statusCode = httpClient.executeMethod(post);

        if (statusCode != HttpStatus.SC_OK) {
            return false;
        }

        InputStream responseStream = post.getResponseBodyAsStream();
        InputStreamReader isr = null;
        BufferedReader br = null;
        StringBuffer response = new StringBuffer();

        try {
            isr = new InputStreamReader(responseStream);
            br = new BufferedReader(isr);
            String line = null;

            while ((line = br.readLine()) != null) {
                response.append(line);
            }
        } finally {
            IOUtils.closeQuietly(br);
            IOUtils.closeQuietly(isr);
            IOUtils.closeQuietly(responseStream);

        }
    } catch (RuntimeException re) {
        throw re;
    } catch (Exception e) {
        return false;
    } finally {
        post.releaseConnection();
    }
    return true;
}

From source file:fr.aliasource.webmail.server.calendar.CalendarProxyImpl.java

@SuppressWarnings("unchecked")
@Override//from w  ww  .j ava2 s  . c o m
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    IAccount ac = (IAccount) req.getSession().getAttribute("account");

    if (ac == null) {
        GWT.log("Account not found in session", null);
        resp.setStatus(HttpServletResponse.SC_FORBIDDEN);
        return;
    }

    PostMethod pm = new PostMethod(backendUrl);
    if (req.getQueryString() != null) {
        pm.setQueryString(req.getQueryString());
    }
    Map<String, String[]> params = req.getParameterMap();
    for (String p : params.keySet()) {
        String[] val = params.get(p);
        pm.setParameter(p, val[0]);
    }

    synchronized (hc) {
        try {
            int ret = hc.executeMethod(pm);
            if (ret != HttpStatus.SC_OK) {
                log("method failed:\n" + pm.getStatusLine() + "\n" + pm.getResponseBodyAsString());
                resp.setStatus(ret);
            } else {
                InputStream is = pm.getResponseBodyAsStream();
                transfer(is, resp.getOutputStream(), false);
            }
        } catch (Exception e) {
            log("error occured on call proxyfication", e);
        } finally {
            pm.releaseConnection();
        }
    }
}

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

/**
 * //from   w  ww.j av a  2s  .co m
 * 
 * @param strURL
 * @param xml
 * @return
 */
public String postXml(String strURL, String xml) {
    // either get the previously stored post or create a new one
    PostMethod post = this.postHolder.get() != null ? this.postHolder.get() : new PostMethod(strURL);
    InputStream xmlStream = null;
    String responseStr = null;
    try {
        xmlStream = new ByteArrayInputStream(xml.getBytes("UTF-8"));
    } catch (UnsupportedEncodingException e) {
        log.error("Unsupport encoding for string: " + xml);
    }
    try {
        post.setRequestEntity(new InputStreamRequestEntity(xmlStream, xml.length()));
        post.addRequestHeader("Content-type", "text/xml; charset=ISO-8859-1");
        HttpClient httpclient = new HttpClient();
        int result = httpclient.executeMethod(post);
        log.debug("Response status code: " + result);
        log.debug("Response body: ");
        responseStr = convertStreamToString(post.getResponseBodyAsStream());
        log.debug(responseStr);
    } catch (IOException e) {
        log.error("error occurred.", e);
    } finally {
        post.releaseConnection();
        // clean up the holder
        postHolder.remove();
    }
    return responseStr;
}

From source file:com.agile_coder.poker.server.stories.steps.BaseSteps.java

protected int createSession() throws IOException {
    String createUrl = BASE_URL;
    HttpClient client = new HttpClient();
    PostMethod post = new PostMethod(createUrl);
    String response;/*from   w  ww  . j  ava2s  .c  om*/
    try {
        executeMethod(client, post);
        response = post.getResponseBodyAsString();
    } finally {
        post.releaseConnection();
    }
    JSONObject obj = JSONObject.fromObject(response);
    return obj.getInt("session");
}

From source file:edu.indiana.d2i.htrc.portal.HTRCExperimentalAnalysisServiceClient.java

public String createVM(String imageName, String loginUerName, String loginPassword, String memory, String vcpu,
        Http.Session session) throws IOException {
    String createVMUrl = PlayConfWrapper.sloanWsEndpoint() + PlayConfWrapper.createVMUrl();

    PostMethod post = new PostMethod(createVMUrl);
    post.addRequestHeader("Authorization", "Bearer " + session.get(PortalConstants.SESSION_TOKEN));
    post.addRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    post.addRequestHeader("htrc-remote-user", session.get(PortalConstants.SESSION_USERNAME));
    post.addRequestHeader("htrc-remote-user-email", session.get(PortalConstants.SESSION_EMAIL));
    post.setParameter("imagename", imageName);
    post.setParameter("loginusername", loginUerName);
    post.setParameter("loginpassword", loginPassword);
    post.setParameter("memory", memory);
    post.setParameter("vcpu", vcpu);
    //        post.setRequestBody((org.apache.commons.httpclient.NameValuePair[]) urlParameters);

    int response = client.executeMethod(post);
    this.responseCode = response;
    if (response == 200) {
        String jsonStr = post.getResponseBodyAsString();
        log.info(Arrays.toString(post.getRequestHeaders()));
        JSONParser parser = new JSONParser();
        try {/*from   w  ww  .  j  ava 2 s . co m*/
            Object obj = parser.parse(jsonStr);
            JSONObject jsonObject = (JSONObject) obj;
            return ((String) jsonObject.get("vmid"));

        } catch (ParseException e) {
            e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
        }
    } else {
        this.responseCode = response;
        log.error(post.getResponseBodyAsString());
        throw new IOException("Response code " + response + " for " + createVMUrl + " message: \n "
                + post.getResponseBodyAsString());
    }
    return null;

}

From source file:fr.aliasource.webmail.server.invitation.GoingInvitationProxyImpl.java

@SuppressWarnings("unchecked")
@Override/*from w  w w .  ja  v a  2  s.  com*/
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    IAccount ac = (IAccount) req.getSession().getAttribute("account");

    if (ac == null) {
        GWT.log("Account not found in session", null);
        resp.setStatus(HttpServletResponse.SC_FORBIDDEN);
        return;
    }

    PostMethod pm = new PostMethod(backendUrl);
    if (req.getQueryString() != null) {
        pm.setQueryString(req.getQueryString());
    }
    Map<String, String[]> params = req.getParameterMap();
    for (String p : params.keySet()) {
        String[] val = params.get(p);
        pm.setParameter(p, val[0]);
    }

    synchronized (hc) {
        try {
            int ret = hc.executeMethod(pm);
            if (ret != HttpStatus.SC_OK) {
                log("method failed:\n" + pm.getStatusLine() + "\n" + pm.getResponseBodyAsString());
                resp.setStatus(ret);
            } else {
                InputStream is = pm.getResponseBodyAsStream();
                transfer(is, resp.getOutputStream(), false);
            }
        } catch (Exception e) {
            log("error occured on call proxyfication", e);
        } finally {
            pm.releaseConnection();
        }
    }
}

From source file:jenkins.plugins.elanceodesk.workplace.notifier.HttpWorker.java

public void run() {
    int tried = 0;
    boolean success = false;
    HttpClient client = getHttpClient();
    client.getParams().setConnectionManagerTimeout(timeout);
    do {// w ww .  j  av  a2 s  .  c om
        tried++;
        RequestEntity requestEntity;
        try {
            requestEntity = new StringRequestEntity(data, "application/json", "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace(logger);
            break;
        }
        logger.println(String.format("Posting data to webhook - %s. Already Tried %s times", url, tried));
        PostMethod post = new PostMethod(url);
        try {
            post.setRequestEntity(requestEntity);
            int responseCode = client.executeMethod(post);
            if (responseCode != HttpStatus.SC_OK) {
                String response = post.getResponseBodyAsString();
                logger.println(String.format(
                        "Posting data to - %s may have failed. Webhook responded with status code - %s", url,
                        responseCode));
                logger.println(String.format("Message from webhook - %s", response));

            } else {
                success = true;
                logger.println(String.format("Posting data to webhook - %s completed ", url));
            }
        } catch (Exception e) {
            logger.println(String.format("Failed to post data to webhook - %s", url));
            e.printStackTrace(logger);
        } finally {
            post.releaseConnection();
        }
    } while (tried < retries && !success);

}

From source file:de.juwimm.cms.common.http.Server2ServerAuthenticationStreamSupportingHttpInvokerRequestExecutor.java

protected PostMethod createPostMethodForStreaming(final HttpInvokerClientConfiguration config)
        throws IOException {
    HttpClientWrapper.getInstance().setHostConfiguration(super.getHttpClient(),
            new URL(config.getServiceUrl()));
    final PostMethod postMethod = new PostMethod(config.getServiceUrl());
    postMethod.setRequestHeader(HTTP_HEADER_CONTENT_TYPE, CONTENT_TYPE_SERIALIZED_OBJECT_WITH_STREAM);
    postMethod.setContentChunked(true);//from  ww  w.jav  a2  s  .  c o  m

    Authentication auth = SecurityContextHolder.getContext().getAuthentication();

    if ((auth != null) && (auth.getName() != null) && (auth.getCredentials() != null)) {
        postMethod.setDoAuthentication(true);
        String base64 = auth.getName() + ":" + auth.getCredentials().toString();
        postMethod.addRequestHeader("Authorization",
                "Basic " + new String(Base64.encodeBase64(base64.getBytes())));

        if (log.isDebugEnabled()) {
            // log.debug("HttpInvocation now presenting via BASIC
            // authentication SecurityContextHolder-derived: " +
            // auth.toString());
            log.debug(
                    "HttpInvocation now presenting via BASIC authentication SecurityContextHolder-derived. User: "
                            + auth.getName());
        }
    } else {
        if (log.isDebugEnabled()) {
            log.debug("Unable to set BASIC authentication header as SecurityContext did not provide "
                    + "valid Authentication: " + auth);
        }
    }
    return postMethod;
}