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:net.sourceforge.jwbf.actions.mw.util.PostModifyContent.java

/**
 * //from  w w w  .  j a va 2s. com
 * @param a the
 * @param tab internal value set
 * @param login a 
 */
public PostModifyContent(final ContentAccessable a, final Hashtable<String, String> tab, LoginData login) {

    String uS = "";
    try {
        uS = "/index.php?title=" + URLEncoder.encode(a.getLabel(), MediaWikiBot.CHARSET) + "&action=submit";
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }

    NameValuePair action = new NameValuePair("wpSave", "Save");
    NameValuePair wpStarttime = new NameValuePair("wpStarttime", tab.get("wpStarttime"));
    NameValuePair wpEditToken = new NameValuePair("wpEditToken", tab.get("wpEditToken"));
    NameValuePair wpEdittime = new NameValuePair("wpEdittime", tab.get("wpEdittime"));

    NameValuePair wpTextbox = new NameValuePair("wpTextbox1", a.getText());

    String editSummaryText = a.getEditSummary();
    if (editSummaryText != null && editSummaryText.length() > 200) {
        editSummaryText = editSummaryText.substring(0, 200);
    }

    NameValuePair wpSummary = new NameValuePair("wpSummary", editSummaryText);

    NameValuePair wpMinoredit = new NameValuePair();

    if (a.isMinorEdit()) {
        wpMinoredit.setValue("1");
        wpMinoredit.setName("wpMinoredit");
    }

    LOG.info("WRITE: " + a.getLabel());
    PostMethod pm = new PostMethod(uS);
    pm.getParams().setContentCharset(MediaWikiBot.CHARSET);

    pm.setRequestBody(new NameValuePair[] { action, wpStarttime, wpEditToken, wpEdittime, wpTextbox, wpSummary,
            wpMinoredit });
    msgs.add(pm);
}

From source file:com.ironiacorp.http.impl.httpclient3.PostRequest.java

public HttpJob call() {
    URI uri = (URI) job.getUri();
    PostMethod postMethod = new PostMethod(uri.toString());
    HttpMethodResult result = new HttpMethodResult();
    postMethod.setRequestBody(parameters.toArray(new NameValuePair[0]));

    try {/*from w w  w  . ja  v a  2  s .c o m*/
        int statusCode = client.executeMethod(postMethod);

        if (statusCode != HttpStatus.SC_OK) {
            System.err.println("Method failed: " + postMethod.getStatusLine());
        }

        InputStream inputStream = postMethod.getResponseBodyAsStream();

        if (inputStream != null) {
            result.setContent(inputStream);
            result.setStatusCode(statusCode);
            job.setResult(result);
        }
    } catch (HttpException e) {
    } catch (IOException e) {
        // In case of an IOException the connection will be released
        // back to the connection manager automatically
    } catch (RuntimeException ex) {
        // In case of an unexpected exception you may want to abort
        // the HTTP request in order to shut down the underlying
        // connection and release it back to the connection manager.
        postMethod.abort();
    }

    return job;
}

From source file:com.amazon.dtasdk.v2.connection.SignatureVerificationTest.java

@Test
public void roundTrip_NoAuth() throws Exception {
    Credential credential = new Credential("SECRETKEY", "KEYID");
    handler.setCredential(credential);/*  ww  w  .ja  v  a 2 s.  c  om*/

    PostMethod method = new PostMethod(serverUrl() + "/path/to/servlet");
    method.setRequestBody("{\"json\": \"value\"}");

    assertEquals(403, client.executeMethod(method));
}

From source file:br.org.acessobrasil.silvinha.util.versoes.VerificadorDeVersoes.java

public boolean verificarVersao(Versao versaoCliente) {
    HttpClient client = new HttpClient();
    PostMethod method = new PostMethod(url);
    NameValuePair param = new NameValuePair("param", "check");
    method.setRequestBody(new NameValuePair[] { param });
    DefaultHttpMethodRetryHandler retryHandler = null;
    retryHandler = new DefaultHttpMethodRetryHandler(0, false);
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, retryHandler);
    try {/*from  w  ww . j a  v a2  s .c o  m*/
        //System.out.println(Silvinha.VERIFICADOR_VERSOES+client.getState().toString());
        int statusCode = client.executeMethod(method);

        if (statusCode != HttpStatus.SC_OK) {
            log.error("Method failed: " + method.getStatusLine());
        }
        // Read the response body.
        byte[] responseBody = method.getResponseBody();
        String rb = new String(responseBody).trim();
        Versao versaoServidor = null;
        try {
            versaoServidor = new Versao(rb);
        } catch (NumberFormatException nfe) {
            return false;
        }
        if (versaoCliente.compareTo(versaoServidor) < 0) {
            AtualizadorDeVersoes av = new AtualizadorDeVersoes(url);
            return av.confirmarAtualizacao();
        } else {
            return false;
        }
    } catch (HttpException he) {
        log.error("Fatal protocol violation: " + he.getMessage(), he);
        return false;
    } catch (IOException ioe) {
        log.error("Fatal transport error: " + ioe.getMessage(), ioe);
        return false;
    } catch (Exception e) {
        return false;
    } finally {
        //Release the connection.
        method.releaseConnection();
    }

}

From source file:com.liaison.service.resources.examples.HelloWorldResource.java

private String sendPost(String authToken) {

    try {/*from  www .j a  v  a 2  s .c  o  m*/

        String JSON_STRING = "{\"oneTimeToken\" : \"{TOKEN}\"}".replace("{TOKEN}", authToken);

        PostMethod postMethod = new PostMethod(POST_URL);
        postMethod.setRequestBody(JSON_STRING);

        // Must send "Content-Type:application/json"
        Header header = new Header("Content-Type", "application/json");

        postMethod.addRequestHeader(header);

        HttpClient httpClient = new HttpClient();

        int statusCode = httpClient.executeMethod(postMethod);

        String response = new String(postMethod.getResponseBody());

        postMethod.releaseConnection();

        return response;

    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:de.sones.mule.demo.transformers.GQLToHttpRequestTransformer.java

@Override
public Object transformMessage(MuleMessage message, String arg1) throws TransformerException {

    try {/* w  ww.  ja v  a2  s . c  om*/

        HttpMethod result;

        //Get the contents of the previous message
        Object src = message.getPayload();

        System.out.println("Body:" + src.toString());

        //Get the endpoint which is configured
        String endpoint = message.getOutboundProperty(MuleProperties.MULE_ENDPOINT_PROPERTY, null);

        System.out.println("Enpoint:" + endpoint);

        //Create an uri
        URI uri = null;

        uri = new URI(endpoint);

        PostMethod postMethod = new PostMethod(uri.toString());

        InputStream is = new ByteArrayInputStream(src.toString().getBytes("UTF-8"));

        postMethod.setRequestBody(src.toString());

        result = postMethod;

        return result;

    } catch (Exception e) {
        throw new TransformerException(this, e);
    }

}

From source file:com.googlecode.fascinator.indexer.SolrSearcher.java

public InputStream get(String query, Map<String, Set<String>> extras, boolean escape) throws IOException {
    if (query == null) {
        query = "*:*";
    } else if (!QUERY_ALL.equals(query) && escape) {
        query = query.replaceAll(":", "\\\\:");
    }//from  w w  w . j  av  a  2  s  .  c o  m
    String selectUrl = baseUrl + "/select";
    NameValuePair[] postData = getPostData(query, extras);
    log.debug("URL:{}, POSTDATA:{}", selectUrl, postData);
    PostMethod method = new PostMethod(selectUrl);
    method.addRequestHeader("Content-type", "application/x-www-form-urlencoded; charset=UTF-8");
    method.setRequestBody(postData);
    int status = client.executeMethod(method, true);
    if (status == HttpStatus.SC_OK) {
        return method.getResponseBodyAsStream();
    }
    return null;
}

From source file:com.amazon.dtasdk.v2.connection.SignatureVerificationTest.java

@Test
public void roundTrip_withPath() throws Exception {
    Credential credential = new Credential("SECRETKEY", "KEYID");
    handler.setCredential(credential);/*from  w w w.ja v a2  s.co m*/

    Request request = new Request(serverUrl() + "/path/to/servlet", Request.Method.POST, "");
    setDefaultHeaders(request);
    request.setBody("{\"json\": \"value\"}");
    signer.sign(request, credential);

    PostMethod method = new PostMethod(request.getUrl());
    copyHeaders(request, method);
    method.setRequestBody(request.getBody());

    assertEquals(200, client.executeMethod(method));
}

From source file:com.krawler.esp.utils.HttpPost.java

public String invoke(String soapMessage) {
    try {/*from  ww  w.j  ava  2  s.c o m*/
        int statusCode = -1;
        String mUri = "http://localhost:7070/service/soap/";
        // the content-type charset will determine encoding used
        // when we set the request body
        PostMethod method = new PostMethod(mUri);
        // method.setRequestHeader("Content-type",
        // getSoapProtocol().getContentType());
        method.setRequestBody(soapMessage);
        method.setRequestContentLength(EntityEnclosingMethod.CONTENT_LENGTH_AUTO);

        // if (getSoapProtocol().hasSOAPActionHeader())
        // method.setRequestHeader("SOAPAction", mUri);

        // execute the method.
        HttpClient mClient = new HttpClient();
        statusCode = mClient.executeMethod(method);

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

        // Release the connection.
        method.releaseConnection();

        // Deal with the response.
        // Use caution: ensure correct character encoding and is not binary
        // data

        String responseStr = toString(responseBody);
        return responseStr;
    } catch (IOException ex) {
        return ex.toString();
    } catch (Exception ex) {
        return ex.toString();
    }
}

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

/**
 * /*w  w  w .  ja  va  2  s.c o m*/
 * @param username
 *            the
 * @param pw
 *            password
 */
public PostLoginOld(final String username, final String pw, final String domain) {
    this.username = username;

    NameValuePair action = new NameValuePair("wpLoginattempt", "Log in");
    NameValuePair url = new NameValuePair("wpRemember", "1");
    NameValuePair userid = new NameValuePair("wpName", username);
    NameValuePair dom = new NameValuePair("wpDomain", domain);

    String pwLabel = "wpPassword";

    NameValuePair password = new NameValuePair(pwLabel, pw);

    PostMethod pm = new PostMethod("/index.php?title=Special:Userlogin&action=submitlogin&type=login");

    pm.getParams().setContentCharset(MediaWikiBot.CHARSET);

    pm.setRequestBody(new NameValuePair[] { action, url, userid, dom, password });

    msgs.add(pm);

}