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:org.apache.camel.component.jetty.HttpRouteTest.java

@Test
public void testPostParameter() throws Exception {
    NameValuePair[] data = { new NameValuePair("request", "PostParameter"),
            new NameValuePair("others", "bloggs") };
    HttpClient client = new HttpClient();
    PostMethod post = new PostMethod("http://localhost:" + port1 + "/parameter");
    post.setRequestBody(data);
    client.executeMethod(post);//  ww  w  .  j a  v a  2 s.c o  m
    InputStream response = post.getResponseBodyAsStream();
    String out = context.getTypeConverter().convertTo(String.class, response);
    assertEquals("Get a wrong output ", "PostParameter", out);
}

From source file:org.apache.cocoon.components.language.markup.xsp.SOAPHelper.java

public XScriptObject invoke() throws ProcessingException {
    HttpConnection conn = null;/*from  w  w  w.  ja  v  a  2 s  .co  m*/

    try {
        if (action == null || action.length() == 0) {
            action = "\"\"";
        }

        String host = url.getHost();
        int port = url.getPort();

        if (System.getProperty("http.proxyHost") != null) {
            String proxyHost = System.getProperty("http.proxyHost");
            int proxyPort = Integer.parseInt(System.getProperty("http.proxyPort"));
            conn = new HttpConnection(proxyHost, proxyPort, host, port);
        } else {
            conn = new HttpConnection(host, port);
        }

        PostMethod method = new PostMethod(url.getFile());
        String request;

        try {
            // Write the SOAP request body
            if (xscriptObject instanceof XScriptObjectInlineXML) {
                // Skip overhead
                request = ((XScriptObjectInlineXML) xscriptObject).getContent();
            } else {
                StringBuffer bodyBuffer = new StringBuffer();
                InputSource saxSource = xscriptObject.getInputSource();

                Reader r = null;
                // Byte stream or character stream?
                if (saxSource.getByteStream() != null) {
                    r = new InputStreamReader(saxSource.getByteStream());
                } else {
                    r = saxSource.getCharacterStream();
                }

                try {
                    char[] buffer = new char[1024];
                    int len;
                    while ((len = r.read(buffer)) > 0)
                        bodyBuffer.append(buffer, 0, len);
                } finally {
                    if (r != null) {
                        r.close();
                    }
                }

                request = bodyBuffer.toString();
            }

        } catch (Exception ex) {
            throw new ProcessingException("Error assembling request", ex);
        }

        method.setRequestHeader(new Header("Content-type", "text/xml; charset=\"utf-8\""));
        method.setRequestHeader(new Header("SOAPAction", action));
        method.setRequestBody(request);

        if (authorization != null && !authorization.equals("")) {
            method.setRequestHeader(
                    new Header("Authorization", "Basic " + SourceUtil.encodeBASE64(authorization)));
        }

        method.execute(new HttpState(), conn);

        String ret = method.getResponseBodyAsString();
        int startOfXML = ret.indexOf("<?xml");
        if (startOfXML == -1) { // No xml?!
            throw new ProcessingException("Invalid response - no xml");
        }

        return new XScriptObjectInlineXML(xscriptManager, ret.substring(startOfXML));
    } catch (Exception ex) {
        throw new ProcessingException("Error invoking remote service: " + ex, ex);
    } finally {
        try {
            if (conn != null)
                conn.close();
        } catch (Exception ex) {
        }
    }
}

From source file:org.apache.cocoon.components.language.markup.xsp.XSPSOAPHelper.java

public XScriptObject invoke() throws ProcessingException {
    HttpConnection conn = null;/*from   ww  w . j  a  v a2s.  com*/

    try {
        if (this.action == null || this.action.length() == 0) {
            this.action = "\"\"";
        }

        String host = this.url.getHost();
        int port = this.url.getPort();
        Protocol protocol = Protocol.getProtocol(this.url.getProtocol());

        if (System.getProperty("http.proxyHost") != null) {
            String proxyHost = System.getProperty("http.proxyHost");
            int proxyPort = Integer.parseInt(System.getProperty("http.proxyPort"));
            conn = new HttpConnection(proxyHost, proxyPort, host, null, port, protocol);
        } else {
            conn = new HttpConnection(host, port, protocol);
        }
        conn.setSoTimeout(1000 * timeoutSeconds);

        PostMethod method = new PostMethod(this.url.getFile());
        String request;

        try {
            // Write the SOAP request body
            if (this.xscriptObject instanceof XScriptObjectInlineXML) {
                // Skip overhead
                request = ((XScriptObjectInlineXML) this.xscriptObject).getContent();
            } else {
                StringBuffer bodyBuffer = new StringBuffer();
                InputSource saxSource = this.xscriptObject.getInputSource();

                Reader r = null;
                // Byte stream or character stream?
                if (saxSource.getByteStream() != null) {
                    r = new InputStreamReader(saxSource.getByteStream());
                } else {
                    r = saxSource.getCharacterStream();
                }

                try {
                    char[] buffer = new char[1024];
                    int len;
                    while ((len = r.read(buffer)) > 0) {
                        bodyBuffer.append(buffer, 0, len);
                    }
                } finally {
                    if (r != null) {
                        r.close();
                    }
                }

                request = bodyBuffer.toString();
            }

        } catch (Exception ex) {
            throw new ProcessingException("Error assembling request", ex);
        }

        method.setRequestHeader(new Header("Content-type", "text/xml; charset=utf-8"));
        method.setRequestHeader(new Header("SOAPAction", this.action));
        method.setRequestBody(request);

        if (this.authorization != null && !this.authorization.equals("")) {
            method.setRequestHeader(
                    new Header("Authorization", "Basic " + SourceUtil.encodeBASE64(this.authorization)));
        }

        method.execute(new HttpState(), conn);

        String contentType = method.getResponseHeader("Content-type").toString();
        // Check if charset given, if not, use defaultResponseEncoding
        // (cannot just use getResponseCharSet() as it fills in
        // "ISO-8859-1" if the charset is not specified)
        String charset = contentType.indexOf("charset=") == -1 ? this.defaultResponseEncoding
                : method.getResponseCharSet();
        String ret = new String(method.getResponseBody(), charset);

        return new XScriptObjectInlineXML(this.xscriptManager, ret);
    } catch (ProcessingException ex) {
        throw ex;
    } catch (Exception ex) {
        throw new ProcessingException("Error invoking remote service: " + ex, ex);
    } finally {
        try {
            if (conn != null) {
                conn.close();
            }
        } catch (Exception ex) {
        }
    }
}

From source file:org.apache.cocoon.generation.HttpProxyGenerator.java

/**
 * Setup this <code>Generator</code> with its runtime configurations and parameters
 * specified in the sitemap, and prepare it for generation.
 *
 * @param sourceResolver The <code>SourceResolver</code> instance resolving sources by
 *                       system identifiers.
 * @param objectModel The Cocoon "object model" <code>Map</code>
 * @param parameters The runtime <code>Parameters</code> instance.
 * @throws ProcessingException If this instance could not be setup.
 * @throws SAXException If a SAX error occurred during setup.
 * @throws IOException If an I/O error occurred during setup.
 * @see #recycle()//from w  ww  .j  ava2 s . c o  m
 */
public void setup(SourceResolver sourceResolver, Map objectModel, String source, Parameters parameters)
        throws ProcessingException, SAXException, IOException {
    /* Do the usual stuff */
    super.setup(sourceResolver, objectModel, source, parameters);

    /*
     * Parameter handling: In case the method is a POST method, query
     * parameters and request parameters will be two different arrays
     * (one for the body, one for the query string, otherwise it's going
     * to be the same one, as all parameters are passed on the query string
     */
    ArrayList req = new ArrayList();
    ArrayList qry = req;
    if (this.method instanceof PostMethod)
        qry = new ArrayList();
    req.addAll(this.reqParams);
    qry.addAll(this.qryParams);

    /*
     * Parameter handling: complete or override the configured parameters with
     * those specified in the pipeline.
     */
    String names[] = parameters.getNames();
    for (int x = 0; x < names.length; x++) {
        String name = names[x];
        String value = parameters.getParameter(name, null);
        if (value == null)
            continue;

        if (name.startsWith("query:")) {
            name = name.substring("query:".length());
            qry.add(new NameValuePair(name, value));
        } else if (name.startsWith("param:")) {
            name = name.substring("param:".length());
            req.add(new NameValuePair(name, value));
        } else if (name.startsWith("query-override:")) {
            name = name.substring("query-override:".length());
            qry = overrideParams(qry, name, value);
        } else if (name.startsWith("param-override:")) {
            name = name.substring("param-override:".length());
            req = overrideParams(req, name, value);
        }
    }

    /* Process the current source URL in relation to the configured one */
    HttpURL src = (super.source == null ? null : new HttpURL(super.source));
    if (this.url != null)
        src = (src == null ? this.url : new HttpURL(this.url, src));
    if (src == null)
        throw new ProcessingException("No URL specified");
    if (src.isRelativeURI()) {
        throw new ProcessingException("Invalid URL \"" + src.toString() + "\"");
    }

    /* Configure the method with the resolved URL */
    HostConfiguration hc = new HostConfiguration();
    hc.setHost(src);
    this.method.setHostConfiguration(hc);
    this.method.setPath(src.getPath());
    this.method.setQueryString(src.getQuery());

    /* And now process the query string (from the parameters above) */
    if (qry.size() > 0) {
        String qs = this.method.getQueryString();
        NameValuePair nvpa[] = new NameValuePair[qry.size()];
        this.method.setQueryString((NameValuePair[]) qry.toArray(nvpa));
        if (qs != null) {
            this.method.setQueryString(qs + "&" + this.method.getQueryString());
        }
    }

    /* Finally process the body parameters */
    if ((this.method instanceof PostMethod) && (req.size() > 0)) {
        PostMethod post = (PostMethod) this.method;
        NameValuePair nvpa[] = new NameValuePair[req.size()];
        post.setRequestBody((NameValuePair[]) req.toArray(nvpa));
    }

    /* Check the debugging flag */
    this.debug = parameters.getParameterAsBoolean("debug", false);
}

From source file:org.apache.cocoon.transformation.SparqlTransformer.java

private void executeRequest(String url, String method, Map httpHeaders, SourceParameters requestParameters)
        throws ProcessingException, IOException, SAXException {
    HttpClient httpclient = new HttpClient();
    if (System.getProperty("http.proxyHost") != null) {
        // getLogger().warn("PROXY: "+System.getProperty("http.proxyHost"));
        String nonProxyHostsRE = System.getProperty("http.nonProxyHosts", "");
        if (nonProxyHostsRE.length() > 0) {
            String[] pHosts = nonProxyHostsRE.replaceAll("\\.", "\\\\.").replaceAll("\\*", ".*").split("\\|");
            nonProxyHostsRE = "";
            for (String pHost : pHosts) {
                nonProxyHostsRE += "|(^https?://" + pHost + ".*$)";
            }/*from   w  w w  .ja va2 s .c  o  m*/
            nonProxyHostsRE = nonProxyHostsRE.substring(1);
        }
        if (nonProxyHostsRE.length() == 0 || !url.matches(nonProxyHostsRE)) {
            try {
                HostConfiguration hostConfiguration = httpclient.getHostConfiguration();
                hostConfiguration.setProxy(System.getProperty("http.proxyHost"),
                        Integer.parseInt(System.getProperty("http.proxyPort", "80")));
                httpclient.setHostConfiguration(hostConfiguration);
            } catch (Exception e) {
                throw new ProcessingException("Cannot set proxy!", e);
            }
        }
    }
    // Make the HttpMethod.
    HttpMethod httpMethod = null;
    // Do not use empty query parameter.
    if (requestParameters.getParameter(parameterName).trim().equals("")) {
        requestParameters.removeParameter(parameterName);
    }
    // Instantiate different HTTP methods.
    if ("GET".equalsIgnoreCase(method)) {
        httpMethod = new GetMethod(url);
        if (requestParameters.getEncodedQueryString() != null) {
            httpMethod.setQueryString(
                    requestParameters.getEncodedQueryString().replace("\"", "%22")); /* Also escape '"' */
        } else {
            httpMethod.setQueryString("");
        }
    } else if ("POST".equalsIgnoreCase(method)) {
        PostMethod httpPostMethod = new PostMethod(url);
        if (httpHeaders.containsKey(HTTP_CONTENT_TYPE) && ((String) httpHeaders.get(HTTP_CONTENT_TYPE))
                .startsWith("application/x-www-form-urlencoded")) {
            // Encode parameters in POST body.
            Iterator parNames = requestParameters.getParameterNames();
            while (parNames.hasNext()) {
                String parName = (String) parNames.next();
                httpPostMethod.addParameter(parName, requestParameters.getParameter(parName));
            }
        } else {
            // Use query parameter as POST body
            httpPostMethod.setRequestBody(requestParameters.getParameter(parameterName));
            // Add other parameters to query string
            requestParameters.removeParameter(parameterName);
            if (requestParameters.getEncodedQueryString() != null) {
                httpPostMethod.setQueryString(
                        requestParameters.getEncodedQueryString().replace("\"", "%22")); /* Also escape '"' */
            } else {
                httpPostMethod.setQueryString("");
            }
        }
        httpMethod = httpPostMethod;
    } else if ("PUT".equalsIgnoreCase(method)) {
        PutMethod httpPutMethod = new PutMethod(url);
        httpPutMethod.setRequestBody(requestParameters.getParameter(parameterName));
        requestParameters.removeParameter(parameterName);
        httpPutMethod.setQueryString(requestParameters.getEncodedQueryString());
        httpMethod = httpPutMethod;
    } else if ("DELETE".equalsIgnoreCase(method)) {
        httpMethod = new DeleteMethod(url);
        httpMethod.setQueryString(requestParameters.getEncodedQueryString());
    } else {
        throw new ProcessingException("Unsupported method: " + method);
    }
    // Authentication (optional).
    if (credentials != null && credentials.length() > 0) {
        String[] unpw = credentials.split("\t");
        httpclient.getParams().setAuthenticationPreemptive(true);
        httpclient.getState().setCredentials(new AuthScope(httpMethod.getURI().getHost(),
                httpMethod.getURI().getPort(), AuthScope.ANY_REALM),
                new UsernamePasswordCredentials(unpw[0], unpw[1]));
    }
    // Add request headers.
    Iterator headers = httpHeaders.entrySet().iterator();
    while (headers.hasNext()) {
        Map.Entry header = (Map.Entry) headers.next();
        httpMethod.addRequestHeader((String) header.getKey(), (String) header.getValue());
    }
    // Declare some variables before the try-block.
    XMLizer xmlizer = null;
    try {
        // Execute the request.
        int responseCode;
        responseCode = httpclient.executeMethod(httpMethod);
        // Handle errors, if any.
        if (responseCode < 200 || responseCode >= 300) {
            if (showErrors) {
                AttributesImpl attrs = new AttributesImpl();
                attrs.addCDATAAttribute("status", "" + responseCode);
                xmlConsumer.startElement(SPARQL_NAMESPACE_URI, "error", "sparql:error", attrs);
                String responseBody = httpMethod.getStatusText(); //httpMethod.getResponseBodyAsString();
                xmlConsumer.characters(responseBody.toCharArray(), 0, responseBody.length());
                xmlConsumer.endElement(SPARQL_NAMESPACE_URI, "error", "sparql:error");
                return; // Not a nice, but quick and dirty way to end.
            } else {
                throw new ProcessingException("Received HTTP status code " + responseCode + " "
                        + httpMethod.getStatusText() + ":\n" + httpMethod.getResponseBodyAsString());
            }
        }
        // Parse the response
        if (responseCode == 204) { // No content.
            String statusLine = httpMethod.getStatusLine().toString();
            xmlConsumer.startElement(SPARQL_NAMESPACE_URI, "result", "sparql:result", EMPTY_ATTRIBUTES);
            xmlConsumer.characters(statusLine.toCharArray(), 0, statusLine.length());
            xmlConsumer.endElement(SPARQL_NAMESPACE_URI, "result", "sparql:result");
        } else if (parse.equalsIgnoreCase("xml")) {
            InputStream responseBodyStream = httpMethod.getResponseBodyAsStream();
            xmlizer = (XMLizer) manager.lookup(XMLizer.ROLE);
            xmlizer.toSAX(responseBodyStream, "text/xml", httpMethod.getURI().toString(),
                    new IncludeXMLConsumer(xmlConsumer));
            responseBodyStream.close();
        } else if (parse.equalsIgnoreCase("text")) {
            xmlConsumer.startElement(SPARQL_NAMESPACE_URI, "result", "sparql:result", EMPTY_ATTRIBUTES);
            String responseBody = httpMethod.getResponseBodyAsString();
            xmlConsumer.characters(responseBody.toCharArray(), 0, responseBody.length());
            xmlConsumer.endElement(SPARQL_NAMESPACE_URI, "result", "sparql:result");
        } else {
            throw new ProcessingException("Unknown parse type: " + parse);
        }
    } catch (ServiceException e) {
        throw new ProcessingException("Cannot find the right XMLizer for " + XMLizer.ROLE, e);
    } finally {
        if (xmlizer != null)
            manager.release((Component) xmlizer);
        httpMethod.releaseConnection();
    }
}

From source file:org.apache.commons.httpclient.demo.FormLoginDemo.java

public static void main(String[] args) throws Exception {
    HttpClient client = new HttpClient();
    client.getHostConfiguration().setHost(LOGON_SITE, LOGON_PORT);

    //login.jsp->main.jsp

    PostMethod post = new PostMethod("/NationWideAdmin/test/FormLoginDemo.jsp");

    NameValuePair name = new NameValuePair("name", "wsq");
    NameValuePair pass = new NameValuePair("password", "1");
    post.setRequestBody(new NameValuePair[] { name, pass });

    //int status = client.executeMethod(post);
    System.out.println(post.getResponseBodyAsString());

    post.releaseConnection();/* www  .ja v  a 2s. com*/

    //cookie

    CookieSpec cookiespec = CookiePolicy.getDefaultSpec();
    Cookie[] cookies = cookiespec.match(LOGON_SITE, LOGON_PORT, "/NationWideAdmin/test/", false,
            client.getState().getCookies());

    if (cookies.length == 0) {
        System.out.println("None");
    } else {
        for (int i = 0; i < cookies.length; i++) {
            System.out.println(cookies[i].toString());
        }
    }

    //main2.jsp

    GetMethod get = new GetMethod("/NationWideAdmin/test/FormLoginDemo1.jsp");
    client.executeMethod(get);
    //System.out.println(get.getResponseBodyAsString());
    //
    String response = new String(get.getResponseBodyAsString().getBytes("8859_1"));
    //
    System.out.println("===================================");
    System.out.println(":");
    System.out.println(response);
    System.out.println("===================================");

    get.releaseConnection();
}

From source file:org.apache.commons.httpclient.demo.PostAFile.java

@SuppressWarnings("deprecation")
public static void main(String[] args) throws IOException {
    HttpClient client = new HttpClient();
    PostMethod postMethod = new PostMethod(url);

    client.setConnectionTimeout(8000);/* w  ww . j a v  a2 s  . c om*/

    // Send any XML file as the body of the POST request
    File f = new File("students.xml");
    System.out.println("File Length = " + f.length());

    postMethod.setRequestBody(new FileInputStream(f));
    postMethod.setRequestHeader("Content-type", "text/xml; charset=ISO-8859-1");

    //int statusCode1 = client.executeMethod(postMethod);
    //
    String response = new String(postMethod.getResponseBodyAsString().getBytes("8859_1"));
    //
    System.out.println("===================================");
    System.out.println(":");
    System.out.println(response);
    System.out.println("===================================");

    System.out.println("statusLine>>>" + postMethod.getStatusLine());
    postMethod.releaseConnection();
}

From source file:org.apache.commons.httpclient.demo.PostXMLClient.java

@SuppressWarnings("deprecation")
public static void main(String[] args) throws Exception {

    File input = new File("test.xml");
    PostMethod post = new PostMethod("http://90.0.12.20:8088/NationWideAdmin/test/PostXMLClient.jsp");

    // //  ww w.  ja v  a2s  . c  o m
    post.setRequestBody(new FileInputStream(input));

    if (input.length() < Integer.MAX_VALUE) {
        post.setRequestContentLength(input.length());
    } else {
        post.setRequestContentLength(EntityEnclosingMethod.CONTENT_LENGTH_CHUNKED);
    }
    // 

    post.setRequestHeader("Content-type", "text/xml; charset=GBK");

    HttpClient httpclient = new HttpClient();
    int result = httpclient.executeMethod(post);
    System.out.println("Response status code: " + result);
    System.out.println("Response body: ");
    System.out.println(post.getResponseBodyAsString());

    post.releaseConnection();
}

From source file:org.apache.commons.httpclient.demo.SimpleHttpClient.java

/**
 * POST//ww w. ja  v a  2 s  .com
 * @return
 */
private static HttpMethod getPostMethod() {
    PostMethod post = new PostMethod("/search2005.php");
    NameValuePair simcard = new NameValuePair("searchkeyword", "1330227");
    post.setRequestBody(new NameValuePair[] { simcard });
    return post;
}

From source file:org.apache.cxf.systest.jaxrs.JAXRSClientServerBookTest.java

@SuppressWarnings("deprecation")
@Test//from w ww.j  av  a 2s.c  om
public void testNoMessageReaderFound() throws Exception {

    String endpointAddress = "http://localhost:" + PORT + "/bookstore/binarybooks";

    PostMethod post = new PostMethod(endpointAddress);
    post.setRequestHeader("Content-Type", "application/octet-stream");
    post.setRequestHeader("Accept", "text/xml");
    post.setRequestBody("Bar");
    HttpClient httpclient = new HttpClient();

    try {
        int result = httpclient.executeMethod(post);
        assertEquals(415, result);
    } finally {
        // Release current connection to the connection pool once you are done
        post.releaseConnection();
    }
}