Example usage for org.jsoup.nodes FormElement elements

List of usage examples for org.jsoup.nodes FormElement elements

Introduction

In this page you can find the example usage for org.jsoup.nodes FormElement elements.

Prototype

Elements elements

To view the source code for org.jsoup.nodes FormElement elements.

Click Source Link

Usage

From source file:de.geeksfactory.opacclient.apis.Open.java

/**
 * Better version of JSoup's implementation of this function ({@link
 * org.jsoup.nodes.FormElement#formData()}).
 *
 * @param form       The form to submit//from w  ww  .java  2 s  . c  o  m
 * @param submitName The name attribute of the button which is clicked to submit the form, or
 *                   null
 * @return A MultipartEntityBuilder containing the data of the form
 */
protected MultipartEntityBuilder formData(FormElement form, String submitName) {
    MultipartEntityBuilder data = MultipartEntityBuilder.create();
    data.setLaxMode();

    // iterate the form control elements and accumulate their values
    for (Element el : form.elements()) {
        if (!el.tag().isFormSubmittable()) {
            continue; // contents are form listable, superset of submitable
        }
        String name = el.attr("name");
        if (name.length() == 0)
            continue;
        String type = el.attr("type");

        if ("select".equals(el.tagName())) {
            Elements options = el.select("option[selected]");
            boolean set = false;
            for (Element option : options) {
                data.addTextBody(name, option.val());
                set = true;
            }
            if (!set) {
                Element option = el.select("option").first();
                if (option != null) {
                    data.addTextBody(name, option.val());
                }
            }
        } else if ("checkbox".equalsIgnoreCase(type) || "radio".equalsIgnoreCase(type)) {
            // only add checkbox or radio if they have the checked attribute
            if (el.hasAttr("checked")) {
                data.addTextBody(name, el.val().length() > 0 ? el.val() : "on");
            }
        } else if ("submit".equalsIgnoreCase(type) || "image".equalsIgnoreCase(type)) {
            if (submitName != null && el.attr("name").contains(submitName)) {
                data.addTextBody(name, el.val());
            }
        } else {
            data.addTextBody(name, el.val());
        }
    }
    return data;
}