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:tools.devnull.jenkins.plugins.buildnotifications.SlackMessage.java

public void send() {
    String[] ids = channelIds.split("\\s*,\\s*");
    HttpClient client = new HttpClient();
    for (String channelId : ids) {
        PostMethod post = new PostMethod("https://slack.com/api/chat.postMessage");

        post.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");

        post.setRequestBody(new NameValuePair[] { new NameValuePair("token", botToken),
                new NameValuePair("as_user", "true"), new NameValuePair("channel", channelId),
                new NameValuePair("text", getMessage()) });
        try {//www  .jav  a2s.  com
            client.executeMethod(post);
        } catch (IOException e) {
            LOGGER.severe("Error while sending notification: " + e.getMessage());
            e.printStackTrace();
        }
    }
}

From source file:tools.devnull.jenkins.plugins.buildnotifications.TelegramMessage.java

public void send() {
    String[] ids = chatIds.split("\\s*,\\s*");
    HttpClient client = new HttpClient();
    for (String chatId : ids) {
        PostMethod post = new PostMethod(String.format("https://api.telegram.org/bot%s/sendMessage", botToken));

        post.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");

        post.setRequestBody(new NameValuePair[] { new NameValuePair("chat_id", chatId),
                new NameValuePair("text", getMessage()) });
        try {//from  w w  w  .  j  a  v  a 2s . c o  m
            client.executeMethod(post);
        } catch (IOException e) {
            LOGGER.severe("Error while sending notification: " + e.getMessage());
            e.printStackTrace();
        }
    }
}

From source file:translate.TRanslate.java

public void post(String input) throws IOException {

    String response = "";
    BufferedReader br = null;//w w  w  .j  a v a  2s  .c  om

    br = new BufferedReader(new FileReader("c:\\test.txt"));
    while ((input = br.readLine()) != null) {

        String body = "text=" + input + "&itc=te-t-i0-und&num=13";
        input = input.replace("  ", "+");
        input = input.replace(" ", "+");
        input = input.replace(",", "+");
        String starting = "\",[\"";
        String ending = "\"],[],{\"";
        PostMethod Postmethod = new PostMethod("https://inputtools.google.com/request");
        Postmethod.addRequestHeader("Host", " inputtools.google.com");
        Postmethod.addRequestHeader("User-Agent",
                " Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.116 Safari/537.36");
        Postmethod.addRequestHeader("Accept",
                "application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,*/*;q=0.5");
        Postmethod.addRequestHeader("Accept-Language", "en-US,en;q=0.8");
        Postmethod.addRequestHeader("Accept-Encoding", "gzip,deflate,sdch");
        Postmethod.addRequestHeader("X-Client-Data", "CKK2yQEIxLbJAQj9lcoB");
        Postmethod.addRequestHeader("Connection", "keepalive,Keep-Alive");
        Postmethod.addRequestHeader("Referer", "http://www.google.com/intl/te/inputtools/try/");
        Postmethod.addRequestHeader("Cookie",
                " GMAIL_RTT=732; HSID=AGUw587xCPSUIaDxj; SSID=AkkKuZaUGVqvz06y7; APISID=Ih-jSJ5j_auXMle3/A8M2u_3miTXEymzjb; SAPISID=ejtl9SxGbj105_1t/Ak0S2KFfQxDfzHxmH; SID=DQAAADcCAAA267hpyJDVmhZXfBKMci856rC5Bt20M4X52m9JnFgK_cqo-_tIsepRyfGNIxjXd5KnchoxbIojLNAegGge80QA3iIH7l6RgYRCFC0NUHGNwTge61j3ATgH7WopBDw_V7PDCSXDV82TzvuXc7s0_ryI7UyWCW9pVANyqNqcBPmFGZbFD4ES2s6VOYs6MW9rVsQyKxTgTnJjv9b0P6cUMvpwr1J-HBGX2mMFqup3wsylJ9Rp1sECSd_bdjunrLKoqcumaV_3XBayFBcn4BZhSYOj3PvA5om7YTL7zWXfYQZfC_i35gZ5VKnGVlSU-mfwZ1TJdztdkQWVAj4r6c2D2gBm6ZKl6P4WtZ9tt3UMq2F0Efh1I1tYGKEW-PCb7zSJI2zupoc63k5VNB4qI8eL-3OzAZoR9BitHnRRe2IKkXdpdaW8dUim-18qqaOeLjQYzFmBGAqxNw8cFEGtyuiUyZGZ6xKVHNAAoW1nFb4E9NGoJtlBo0nYf0kL4tg68g-kOc9GK5WD28pKQbHuFvlgieSRsvX1R3FftEZs-FMTU-KEZgniOssOeXLD7Qupnh37KbXRysPpkgNf72JdaIodIALUoM4k-6mHgUU-r0uLXNWYigGhvt72qVcuSH6uBHuoOUSee838n_k0E8-vg6bpPis_dg5A30Aq2wLGtFS5Q72Qw3hflukKGHvL64wW2vEvUZq3xtMS685Yx1_ZN72A8-YbB8lHEARnTLrm9ticp1q4X2Zsiz-wMtrq6qU4pRALEKE; OGP=-5061574:; OGPC=5061940-3:5061952-24:5061574-2:5061975-17:; NID=77=S4GVPPNrqG49rmLeZbOwlcNB_PTo1_UNBiv6k2q3RV1O_RY14vKc25tuRyt2IhIvd3ntYrgMgb1WpPUeonBk3CMik5PuqeEYUkjOH6C0Sdg2Xgbl_DxAja0Z0o-gJBolOvyKBMo1YM8MYDVSBJl4dPVRxVvTyg68tGAUmP6Ic6EwDk25g5nA6DMH8nhiyQOT7cG3Zz1Irt2GRhMvqo6jYugcIUTNnogFDBY2Cy-hw9MbLvM8PX1_KRWhwvgKpnR4SwwcqMhQXDYUAPeYjlRGJysIBsS1E0OIPw8xhcKOAGLmN7Jyuwa9FZsHZlEPBXY; S=grandcentral=bhpk116omdw5GfDWh1bWOQ:billing-ui-v3=-hfCJx7YhccZsFolsRi1KA:billing-ui-v3-efe=-hfCJx7YhccZsFolsRi1KA");

        Postmethod.addRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        Postmethod.setRequestBody(body);
        Postmethod.addRequestHeader("Content-Length", "" + body.length());
        Postmethod.getFollowRedirects();

        try {
            HttpClient client = new HttpClient();

            client.executeMethod(Postmethod);

            Reader reader = null;

            StringWriter writer = null;

            String charset = "UTF-8"; // You should determine it based on response header.

            try {

                InputStream ungzippedResponse = null;

                ungzippedResponse = new GZIPInputStream(Postmethod.getResponseBodyAsStream());
                reader = new InputStreamReader(ungzippedResponse, charset);

                writer = new StringWriter();

                char[] buffer = new char[10240];

                for (int length = 0; (length = reader.read(buffer)) > 0;) {

                    writer.write(buffer, 0, length);
                }
                writer.close();
                reader.close();
                response = writer.toString();

            } catch (Exception ex) {
                ex.printStackTrace();
            }
            int pos = 0;
            int n1 = 0;
            int n2 = 0;
            while (n1 >= 0) {
                n1 = response.indexOf(starting, n2);
                n2 = response.indexOf(ending, n1);
                if (n1 > 0 && n2 > 0)
                    System.out.println(response.substring(n1 + starting.length(), n2));

            }

        } catch (Exception m) {

            m.printStackTrace();
        }

    }
}

From source file:vle.domain.webservice.http.impl.HttpRestTransportImpl.java

/**
 * @see net.sf.sail.webapp.domain.webservice.http.HttpRestTransport#post(net.sf.sail.webapp.domain.webservice.http.HttpPostRequest)
 *///from w  w w . j  av  a2  s  .  c  om
public PostMethod post(final HttpPostRequest httpPostRequestData) throws HttpStatusCodeException {
    final PostMethod method = new PostMethod(this.baseUrl + httpPostRequestData.getRelativeUrl());

    this.setHeaders(httpPostRequestData, method);

    // set body data
    final String bodyData = httpPostRequestData.getBodyData();
    //if (StringUtils.hasText(bodyData)) {
    //   method.setRequestEntity(new StringRequestEntity(bodyData));
    //}

    // set parameters
    final Map<String, String> requestParameters = httpPostRequestData.getRequestParameters();
    if (requestParameters != null && !requestParameters.isEmpty()) {
        final Set<String> keys = requestParameters.keySet();
        for (Iterator<String> i = keys.iterator(); i.hasNext();) {
            String key = i.next();
            method.addParameter(key, requestParameters.get(key));
        }
    }

    final Map<String, String> responseHeaders = new HashMap<String, String>();
    try {
        // Execute the method.
        logRequest(method, bodyData);
        method.addParameter("status", "abc");
        NameValuePair[] arr = new NameValuePair[] { new NameValuePair("status", "good") };
        method.setRequestBody(arr);
        method.setRequestBody(bodyData);
        final int statusCode = this.client.executeMethod(method);
        httpPostRequestData.isValidResponseStatus(method, statusCode);
        final Header[] headers = method.getResponseHeaders();
        for (int i = 0; i < headers.length; i++) {
            responseHeaders.put(headers[i].getName(), headers[i].getValue());
        }
    } catch (HttpException e) {
        logAndThrowRuntimeException(e);
    } catch (IOException e) {
        logAndThrowRuntimeException(e);
    } finally {
        method.releaseConnection();
    }

    return method;
}

From source file:zz.pseas.ghost.utils.HttpClinetUtil.java

/**
 * @author GS//from  ww  w . j  a v a2s.  c om
 * @param url
 * @param para
 *            Post??
 * @return
 * @throws IOException
 */
public static String post(String url, Map<String, String> para) throws IOException {
    String responseBody = null;
    PostMethod postMethod = new PostMethod(url);
    NameValuePair[] data = new NameValuePair[para.size()];
    int index = 0;
    for (String s : para.keySet()) {
        data[index++] = new NameValuePair(s, para.get(s));
    }
    postMethod.setRequestBody(data); // ?
    try {
        int statusCode = hc.executeMethod(postMethod);
        if (statusCode != HttpStatus.SC_OK) {
            LOG.error("Method failed: " + postMethod.getStatusLine());
        }
        responseBody = postMethod.getResponseBodyAsString();
    } catch (UnknownHostException e) {
        e.printStackTrace();
        LOG.error("??" + e.getMessage());
    } catch (HttpException e) {
        e.printStackTrace();
        LOG.error(e.getMessage());
    } catch (IOException e) {
        e.printStackTrace();
        LOG.error(e.getMessage());
    } finally {
        postMethod.releaseConnection(); // 
    }
    return responseBody;
}

From source file:zz.pseas.ghost.utils.HttpClinetUtil.java

/**
 * @author GS//from ww w  . j ava 2  s . c  o  m
 * @param url
 * @param para
 * @param cookie
 * @return
 * @throws IOException
 */
public static String post(String url, Map<String, String> para, String cookie) throws IOException {
    String responseBody = null;
    PostMethod postMethod = new PostMethod(url);
    NameValuePair[] data = new NameValuePair[para.size()];
    int index = 0;
    for (String s : para.keySet()) {
        data[index++] = new NameValuePair(s, para.get(s));
    }
    postMethod.setRequestBody(data); // ?
    if (!cookie.equals("")) {
        postMethod.setRequestHeader("cookie", cookie);
    }
    try {
        int statusCode = hc.executeMethod(postMethod);
        if (statusCode != HttpStatus.SC_OK) {
            LOG.error("Method failed: " + postMethod.getStatusLine());
        }
        responseBody = postMethod.getResponseBodyAsString();
    } catch (SocketTimeoutException e) {
        e.printStackTrace();
        LOG.error("??" + e.getMessage());
    } catch (UnknownHostException e) {
        e.printStackTrace();
        LOG.error("??" + e.getMessage());
    } catch (HttpException e) {
        e.printStackTrace();
        LOG.error(e.getMessage());
    } catch (IOException e) {
        e.printStackTrace();
        LOG.error(e.getMessage());
    } finally {
        postMethod.releaseConnection(); // 
    }
    return responseBody;
}