Example usage for org.apache.commons.httpclient NameValuePair NameValuePair

List of usage examples for org.apache.commons.httpclient NameValuePair NameValuePair

Introduction

In this page you can find the example usage for org.apache.commons.httpclient NameValuePair NameValuePair.

Prototype

public NameValuePair(String name, String value) 

Source Link

Document

Constructor.

Usage

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   www.  j  a  va2 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.generation.HttpProxyGenerator.java

/**
 * Prepare a map of parameters from an array of <code>Configuration</code>
 * items.//w  w  w . jav  a2 s  . c o  m
 *
 * @param configurations An array of <code>Configuration</code> elements.
 * @return A <code>List</code> of <code>NameValuePair</code> elements.
 * @throws ConfigurationException If a parameter doesn't specify a name.
 */
private ArrayList getParams(Configuration configurations[]) throws ConfigurationException {
    ArrayList list = new ArrayList();

    if (configurations.length < 1)
        return (list);

    for (int x = 0; x < configurations.length; x++) {
        Configuration configuration = configurations[x];
        String name = configuration.getAttribute("name", null);
        if (name == null) {
            throw new ConfigurationException(
                    "No name specified for parameter at " + configuration.getLocation());
        }

        String value = configuration.getAttribute("value", null);
        if (value != null)
            list.add(new NameValuePair(name, value));

        Configuration subconfigurations[] = configuration.getChildren("value");
        for (int y = 0; y < subconfigurations.length; y++) {
            value = subconfigurations[y].getValue(null);
            if (value != null)
                list.add(new NameValuePair(name, value));
        }
    }

    return (list);
}

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

/**
 * Override the value for a named parameter in a specfied <code>ArrayList</code>
 * or add it if the parameter was not found.
 *
 * @param list The <code>ArrayList</code> where the parameter is stored.
 * @param name The parameter name.//from  w w w .ja  v  a 2  s.  c o  m
 * @param value The new parameter value.
 * @return The same <code>List</code> of <code>NameValuePair</code> elements.
 */
private ArrayList overrideParams(ArrayList list, String name, String value) {
    Iterator iterator = list.iterator();
    while (iterator.hasNext()) {
        NameValuePair param = (NameValuePair) iterator.next();
        if (param.getName().equals(name)) {
            iterator.remove();
            break;
        }
    }
    list.add(new NameValuePair(name, value));
    return (list);
}

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

/**
 * Forwards the request and returns the response.
 * //from   w w  w  .  j a v  a  2  s  .  co  m
 * The rest is probably out of date:
 * Will use a UrlGetMethod to benefit the cacheing mechanism
 * and intermediate proxy servers.
 * It is potentially possible that the size of the request
 * may grow beyond a certain limit for GET and it will require POST instead.
 *
 * @return byte[] XML response
 */
public byte[] fetch() throws ProcessingException {
    HttpMethod method = null;

    // check which method (GET or POST) to use.
    if (this.configuredHttpMethod.equalsIgnoreCase(METHOD_POST)) {
        method = new PostMethod(this.source);
    } else {
        method = new GetMethod(this.source);
    }

    if (this.getLogger().isDebugEnabled()) {
        this.getLogger().debug("request HTTP method: " + method.getName());
    }

    // this should probably be exposed as a sitemap option
    method.setFollowRedirects(true);

    // copy request parameters and merge with URL parameters
    Request request = ObjectModelHelper.getRequest(objectModel);

    ArrayList paramList = new ArrayList();
    Enumeration enumeration = request.getParameterNames();
    while (enumeration.hasMoreElements()) {
        String pname = (String) enumeration.nextElement();
        String[] paramsForName = request.getParameterValues(pname);
        for (int i = 0; i < paramsForName.length; i++) {
            NameValuePair pair = new NameValuePair(pname, paramsForName[i]);
            paramList.add(pair);
        }
    }

    if (paramList.size() > 0) {
        NameValuePair[] allSubmitParams = new NameValuePair[paramList.size()];
        paramList.toArray(allSubmitParams);

        String urlQryString = method.getQueryString();

        // use HttpClient encoding routines
        method.setQueryString(allSubmitParams);
        String submitQryString = method.getQueryString();

        // set final web service query string

        // sometimes the querystring is null here...
        if (null == urlQryString) {
            method.setQueryString(submitQryString);
        } else {
            method.setQueryString(urlQryString + "&" + submitQryString);
        }

    } // if there are submit parameters

    byte[] response = null;
    try {
        int httpStatus = httpClient.executeMethod(method);
        if (httpStatus < 400) {
            if (this.getLogger().isDebugEnabled()) {
                this.getLogger().debug("Return code when accessing the remote Url: " + httpStatus);
            }
        } else {
            throw new ProcessingException("The remote returned error " + httpStatus
                    + " when attempting to access remote URL:" + method.getURI());
        }
    } catch (URIException e) {
        throw new ProcessingException("There is a problem with the URI: " + this.source, e);
    } catch (IOException e) {
        try {
            throw new ProcessingException(
                    "Exception when attempting to access the remote URL: " + method.getURI(), e);
        } catch (URIException ue) {
            throw new ProcessingException("There is a problem with the URI: " + this.source, ue);
        }
    } finally {
        /* It is important to always read the entire response and release the
         * connection regardless of whether the server returned an error or not.
         * {@link http://jakarta.apache.org/commons/httpclient/tutorial.html}
         */
        response = method.getResponseBody();
        method.releaseConnection();
    }

    return response;
}

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

protected void endNvpElement() {
    switch (current_state) {
    case SethTransformer.STATE_INSIDE_NVP_ELEMENT:
        String parmVal = current_value.toString().trim();
        //examples of extra encoding options
        /*//from  w w w  .j  a  va  2 s .  c om
        try {
            parmVal = URIUtil.encodeQuery(parmVal);
        } catch (URIException uriEx) {
            System.out.println("prob: " + uriEx.toString());
            parmVal = current_value.toString().trim();
        } */
        /*
        try {
            parmVal = URLEncoder.encode(parmVal,"UTF-8");
        } catch (UnsupportedEncodingException uriEx) {
            System.out.println("prob: " + uriEx.toString());
            parmVal = current_value.toString().trim();
        }
        */

        //we can't always rely on uri encodings for whitespaces
        if (getCurrentRetrieval().jsspace != null)
            parmVal = parmVal.replaceAll(" ", "\\\\u0020");

        NameValuePair thisNVP = new NameValuePair(getCurrentRetrieval().nvpName, parmVal);

        getCurrentRetrieval().nvps.addElement(thisNVP);
        current_state = getCurrentRetrieval().toDo;
        break;
    default:
        throwIllegalStateException("Not expecting a end nvp element");
    }//switch
}

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();/*from  w  w  w . jav a 2  s.c om*/

    //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.SimpleHttpClient.java

/**
 * POST//from  w ww . j av  a2  s  . c  om
 * @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.commons.httpclient.demo.SubmitHttpForm.java

public static void main(String[] args) {

    //Instantiate an HttpClient
    HttpClient client = new HttpClient();

    //Instantiate a GET HTTP method
    //HttpMethod method = new GetMethod(url);
    //Instantiate a POST HTTP method
    PostMethod method = new PostMethod(url);

    //Define name-value pairs to set into the QueryString
    NameValuePair nvp1 = new NameValuePair("firstName", "fname");
    NameValuePair nvp2 = new NameValuePair("lastName", "lname");
    NameValuePair nvp3 = new NameValuePair("email", "email@email.com");

    method.setQueryString(new NameValuePair[] { nvp1, nvp2, nvp3 });

    try {//from   ww w . j  a  v  a  2 s .  c  om
        int statusCode = client.executeMethod(method);

        System.out.println("QueryString>>> " + method.getQueryString());
        System.out.println("Status Text>>> " + HttpStatus.getStatusText(statusCode));

        //Get data as a String
        //
        String response = new String(method.getResponseBodyAsString().getBytes("8859_1"));
        //
        System.out.println("===================================");
        System.out.println(":");
        System.out.println(response);
        System.out.println("===================================");

        //OR as a byte array
        byte[] res = method.getResponseBody();

        //write to file
        FileOutputStream fos = new FileOutputStream("donepage.html");
        fos.write(res);

        //release connection
        method.releaseConnection();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:org.apache.excalibur.source.factories.HTTPClientSource.java

/**
 * Factory method to create a new {@link PostMethod} with the given
 * {@link SourceParameters} object.// w ww. jav  a 2s. co m
 *
 * @param uri URI
 * @param params {@link SourceParameters}
 * @return a {@link PostMethod} instance
 */
private PostMethod createPostMethod(final String uri, final SourceParameters params) {
    final PostMethod post = new PostMethod(uri);

    if (params == null) {
        return post;
    }

    for (final Iterator names = params.getParameterNames(); names.hasNext();) {
        final String name = (String) names.next();

        for (final Iterator values = params.getParameterValues(name); values.hasNext();) {
            final String value = (String) values.next();
            post.addParameter(new NameValuePair(name, value));
        }
    }

    return post;
}

From source file:org.apache.forrest.solr.client.SolrSearchGenerator.java

private PostMethod preparePost() {
    PostMethod filePost = new PostMethod(destination);
    filePost.addRequestHeader("User-Agent", AGENT);
    Iterator keys = map.keySet().iterator();
    HashSet set = new HashSet();
    while (keys.hasNext()) {
        String element = (String) keys.next();
        if (!QUERY_PARAM.equals(element)) {
            String value = (String) map.get(element);
            set.add(new NameValuePair(element, value));
        }//from ww  w . ja va  2s. c om
    }
    //make sure we send the query (even if null) to get a response
    set.add(new NameValuePair(QUERY_PARAM, query));
    for (Iterator iter = set.iterator(); iter.hasNext();) {
        filePost.addParameter((NameValuePair) iter.next());
    }
    return filePost;
}