2012-11-04 87 views
1

我想使用Jsoup和HttpClient自動發佈大量HTML表單。這些表單中的大多數都有隱藏字段(包括會話ID等),或者有我寧願單獨留下的默認值。使用Jsoup獲取表單中的所有名稱/值對

單獨編寫每個表單提交 - 從頁面提取每個隱藏或默認值 - 是非常乏味的,所以我想寫一個通用方法來獲取給定表單的HTTP參數列表。但它並不是一段簡單的代碼,因爲各種各樣的輸入標籤和字段類型,每一種都可能需要特定的處理(例如textareas,複選框,單選按鈕,選擇...),所以我我以爲如果它已經存在,我會先搜索/詢問。

注意:Jsoup和HttpClient是給定的;我無法改變 - 所以請不要提供建議其他解決方案的答案:我有一個Jsoup Document對象,我需要構建一個HttpClient HttpRequest。

回答

3

所以我寫完了。我仍然希望交換經過實地測試(並希望在其他地方維護)的東西,但如果它可以幫助任何人在這裏登陸...

未經過徹底測試,並且不支持multipar/form-data,但適用於我試過的幾個例子:

public void submit(String formSelector, List<String> params) { 
    if (params.size() % 2 != 0) { 
     throw new Exception("There must be an even number of params."); 
    } 

    Element form= $(formSelector).first(); 

    Set<String> newParams= Sets.newHashSet(); 
    for (int i=0; i < params.size(); i+= 2) { 
     newParams.add(params.get(i)); 
    } 

    List<String> allParams= Lists.newArrayList(params); 
    for (Element field: form.select("input, select, textarea")) { 
     String name= field.attr("name"); 
     if (name == null || newParams.contains(name)) continue; 
     String type= field.attr("type").toLowerCase(); 
     if ("checkbox".equals(type) || "radio".equals(type)) { 
     if (field.attr("checked") != null) { 
      allParams.add(field.attr("name")); 
      allParams.add(field.attr("value")); 
     } 
     } 
     else if (! fieldTypesToIgnore.contains(type)) { 
     allParams.add(field.attr("name")); 
     allParams.add(field.val()); 
     } 
    } 

    String action= form.attr("abs:action"); 
    String method= form.attr("method").toLowerCase(); 
    // String encType= form.attr("enctype"); -- TODO 

    if ("post".equals(method)) { 
     post(action, allParams); 
    } 
    else { 
     get(action, allParams); 
    } 
    } 

($,get和post是我已經躺在身邊的方法......你可以很容易地猜出他們做了什麼)。

0

Jsoup在FormElement類中有formData方法;它在簡單的情況下工作,但它並不總是做我需要的,所以我最終也寫了一些自定義代碼。

相關問題