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:mesquite.tol.lib.BaseHttpRequestMaker.java

public static byte[] doPost(String url, Map additionalParameters) {
    PostMethod xmlPost = new PostMethod(url);
    NameValuePair[] argsArray = new NameValuePair[additionalParameters.keySet().size()];
    int i = 0;//from  w  w  w .  j  a v a2 s  .com
    for (Iterator iter = additionalParameters.keySet().iterator(); iter.hasNext();) {
        String nextParamName = (String) iter.next();
        String nextValue = (String) additionalParameters.get(nextParamName);
        argsArray[i++] = new NameValuePair(nextParamName, nextValue);
    }
    xmlPost.setRequestBody(argsArray);
    return executePost(xmlPost);
}

From source file:com.glaf.core.util.http.CommonsHttpClientUtils.java

/**
 * ??POST/*from   w  w w.  java 2  s  .co  m*/
 * 
 * @param url
 *            ??
 * @param encoding
 *            
 * @param dataMap
 *            ?
 * 
 * @return
 */
public static String doPost(String url, String encoding, Map<String, String> dataMap) {
    PostMethod method = null;
    String content = null;
    try {
        method = new PostMethod(url);
        method.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, encoding);
        method.addRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=" + encoding);
        if (dataMap != null && !dataMap.isEmpty()) {
            NameValuePair[] nameValues = new NameValuePair[dataMap.size()];
            int i = 0;
            for (Map.Entry<String, String> entry : dataMap.entrySet()) {
                String name = entry.getKey().toString();
                String value = entry.getValue();
                nameValues[i] = new NameValuePair(name, value);
                i++;
            }
            method.setRequestBody(nameValues);
        }
        HttpClient client = new HttpClient();
        int status = client.executeMethod(method);
        if (status == HttpStatus.SC_OK) {
            content = method.getResponseBodyAsString();
        }
    } catch (IOException ex) {
        throw new RuntimeException(ex);
    } finally {
        if (method != null) {
            method.releaseConnection();
            method = null;
        }
    }
    return content;
}

From source file:es.uvigo.ei.sing.jarvest.core.HTTPUtils.java

public synchronized static InputStream doPost(String urlstring, String queryString, String separator,
        Map<String, String> additionalHeaders, StringBuffer charsetb) throws HttpException, IOException {
    System.err.println("posting to: " + urlstring + ". query string: " + queryString);
    HashMap<String, String> query = parseQueryString(queryString, separator);
    HttpClient client = getClient();/*from www . ja v  a 2s  .c om*/

    URL url = new URL(urlstring);
    int port = url.getPort();
    if (port == -1) {
        if (url.getProtocol().equalsIgnoreCase("http")) {
            port = 80;
        }
        if (url.getProtocol().equalsIgnoreCase("https")) {
            port = 443;
        }
    }

    client.getHostConfiguration().setHost(url.getHost(), port, url.getProtocol());
    client.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);

    final PostMethod post = new PostMethod(url.getFile());
    addHeaders(additionalHeaders, post);
    post.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    post.setRequestHeader("Accept", "*/*");
    // Prepare login parameters
    NameValuePair[] valuePairs = new NameValuePair[query.size()];

    int counter = 0;

    for (String key : query.keySet()) {
        //System.out.println("Adding pair: "+key+": "+query.get(key));
        valuePairs[counter++] = new NameValuePair(key, query.get(key));

    }

    post.setRequestBody(valuePairs);
    //authpost.setRequestEntity(new StringRequestEntity(requestEntity));

    client.executeMethod(post);

    int statuscode = post.getStatusCode();
    InputStream toret = null;
    if ((statuscode == HttpStatus.SC_MOVED_TEMPORARILY) || (statuscode == HttpStatus.SC_MOVED_PERMANENTLY)
            || (statuscode == HttpStatus.SC_SEE_OTHER) || (statuscode == HttpStatus.SC_TEMPORARY_REDIRECT)) {
        Header header = post.getResponseHeader("location");
        if (header != null) {
            String newuri = header.getValue();
            if ((newuri == null) || (newuri.equals(""))) {
                newuri = "/";
            }

        } else {
            System.out.println("Invalid redirect");
            System.exit(1);
        }
    } else {
        charsetb.append(post.getResponseCharSet());
        final InputStream in = post.getResponseBodyAsStream();

        toret = new InputStream() {

            @Override
            public int read() throws IOException {
                return in.read();
            }

            @Override
            public void close() {
                post.releaseConnection();
            }

        };

    }

    return toret;
}

From source file:net.sourceforge.jwbf.actions.mw.old.PostDelete.java

/**
 * /*from w  w w  .jav  a2  s .  co  m*/
 * @param label of the article
 * @param tab with contains environment variable "wpEditToken"
 * @deprecated
 */
public PostDelete(final String label, Hashtable<String, String> tab) {

    NameValuePair action = new NameValuePair("wpConfirmB", "Delete Page");
    // this value is preseted
    NameValuePair wpReason = new NameValuePair("wpReason", "hier der Grund");
    wpReason.setName("backdraft");

    NameValuePair wpEditToken = new NameValuePair("wpEditToken", tab.get("wpEditToken"));

    PostMethod pm = new PostMethod("/index.php?title=" + label + "&action=delete");

    pm.setRequestBody(new NameValuePair[] { action, wpReason, wpEditToken });
    pm.getParams().setContentCharset(MediaWikiBot.CHARSET);
    msgs.add(pm);

}

From source file:com.appenginefan.toolkit.common.HttpClientEnvironment.java

@Override
public String fetch(String data) {
    LOG.fine("sending " + data);
    PostMethod method = new PostMethod(url);
    method.setRequestBody(data);
    try {//from w w w . j a va 2 s .c  o m
        int returnCode = client.executeMethod(method);
        if (returnCode == HttpStatus.SC_OK) {
            String response = method.getResponseBodyAsString();
            LOG.fine("receiving " + response);
            return response;
        } else {
            LOG.log(Level.WARNING, "Communication failed, status code " + returnCode);
        }
    } catch (HttpException e) {
        LOG.log(Level.WARNING, "Communication failed ", e);
    } catch (IOException e) {
        LOG.log(Level.WARNING, "Communication failed ", e);
    } finally {
        method.releaseConnection();
    }
    return null;
}

From source file:com.voidsearch.voidbase.client.VoidBaseHttpClient.java

protected void post(VoidBaseQuery query, String content) throws Exception {

    PostMethod post = new PostMethod(query.getQuery());
    post.setRequestBody(content);

    try {// w w  w.  j a  v a 2 s.  c om
        client.executeMethod(post);
        post.getResponseBodyAsStream(); // ignore response
    } catch (HttpException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        post.releaseConnection();
    }
}

From source file:com.ohalo.baidu.map.BaiduMapTest.java

/**
 * //from w w  w.  ja va2s .com
 * <pre>
 * ??
 * 
 * 2013-10-8
 * </pre>
 * 
 * @throws IllegalArgumentException
 * @throws IOException
 */
public void testSearchCompanyDetailInfo() throws IllegalArgumentException, IOException {
    HttpClient client = new HttpClient();
    PostMethod method = new PostMethod("http://www.sgs.gov.cn/lz/etpsInfo.do?method=viewDetail");
    method.setRequestBody(new NameValuePair[] { new NameValuePair("etpsId", "150000022004032200107") });
    client.executeMethod(method);
    String response = new String(method.getResponseBody());
    System.out.println(response);
}

From source file:com.ohalo.baidu.map.BaiduMapTest.java

/**
 * /*from ww  w .j  av  a  2s. c  o  m*/
 * <pre>
 * ??
 * 
 * 2013-10-8
 * </pre>
 * 
 * @throws IllegalArgumentException
 * @throws IOException
 */
public void testSearchCompanyBaseInfo() throws IllegalArgumentException, IOException {
    HttpClient client = new HttpClient();
    PostMethod method = new PostMethod("http://www.sgs.gov.cn/lz/etpsInfo.do?method=doSearch");
    method.setRequestBody(new NameValuePair[] {
            new NameValuePair("keyWords",
                    new String("??".getBytes(), "ISO8859-1")),
            new NameValuePair("searchType", "1") });
    client.executeMethod(method);
    String response = new String(method.getResponseBody());
    System.out.println(response);
}

From source file:net.sourceforge.jwbf.actions.mw.login.PostLogin.java

/**
 * // ww w. j  ava  2  s  .c o m
 * @param username the
 * @param pw password
 */
public PostLogin(final String username, final String pw) {

    NameValuePair userid = new NameValuePair("lgname", username);
    NameValuePair password = new NameValuePair("lgpassword", pw);

    PostMethod pm = new PostMethod("/api.php?action=login&format=xml");

    pm.setRequestBody(new NameValuePair[] { userid, password });
    pm.getParams().setContentCharset(MediaWikiBot.CHARSET);
    msgs.add(pm);

}

From source file:jshm.sh.client.HttpForm.java

/**
 * //w  ww .j a v a  2s.  c o  m
 * @param method Is an {@link Object} for the purpose of overloading the constructor
 * @param url
 * @param data An array of Strings with alternating keys and values
 */
public HttpForm(final String method, final Object url, final String... data) {
    if ((data.length & 1) != 0)
        throw new IllegalArgumentException("data must have an even number of values");
    if (!(url instanceof String))
        throw new IllegalArgumentException("url must be a String");

    this.url = (String) url;
    this.data = new NameValuePair[data.length / 2];

    // this.data[0] = data[0], data[1]
    // this.data[1] = data[2], data[3]
    // this.data[2] = data[4], data[5]
    for (int i = 0; i < data.length; i += 2) {
        this.data[i / 2] = new NameValuePair(data[i], data[i + 1]);
    }

    this.methodName = method;

    if ("POST".equalsIgnoreCase(method.toString())) {
        PostMethod postMethod = new PostMethod(this.url);
        postMethod.setRequestBody(this.data);
        this.method = postMethod;
    } else if ("GET".equalsIgnoreCase(method.toString())) {
        GetMethod getMethod = new GetMethod(this.url);
        getMethod.setQueryString(this.data);
        this.method = getMethod;
    } else {
        throw new IllegalArgumentException("method must be POST or GET, given: " + method);
    }
}