使用 Aspose.HTML for Java 编辑 HTML 表单

HTML 表格元素

HTMLFormElement 类表示一个包含输入控件的部分,用于提交用户信息。使用 Aspose.HTML for Java,您可以轻松完成 HTML 表单,并直接从 Java 应用程序发送数据。为了使这一过程更加方便,我们设计了 com.aspose.html.forms 包。该软件包的主要元素是 FormEditor。通过它,您可以在文档中查找现有表单、从头开始创建新表单、遍历元素、填充数据并将信息发送到远程服务器。本文将介绍如何使用 FormEditor 对象。

在本文中,您将学习如何使用 FormEditor 对象来操作文档中的 HTML 表单、输入控件和提交信息。在本文中,我们使用 https://httpbin.org 服务设计的表单进行测试。

如何在 Java 中使用 FormEditor

以下代码片段演示了如何使用 Aspose.HTML for Java 库以编程方式填写和提交 HTML 表单:

  1. 使用 HTMLDocument(url) 构造函数创建 HTMLDocument 类的新实例。指定要填写和提交的 HTML 表单的 URL。
  2. 使用create(document, index) 方法创建 FormEditor 类的实例,并在其中传递 HTMLDocument 实例和要编辑的表单的索引(值 0 指 HTML 文档中的第一个表单)。
  3. 使用 com.aspose.html.forms 包中的类和方法填写数据,并将填写好的 HTML 表单保存到文件中。
  4. 创建 FormSubmitter 类的实例。
  5. 调用 FormSubmitter 类的 submit() 方法,将表单数据提交到远程服务器。
  6. 使用 isSuccess() 方法检查表单提交结果的状态。
 1// Fill out and submit an HTML form programmatically using Aspose.HTML for Java
 2
 3// Initialize an instance of HTML document from "https://httpbin.org/forms/post" url
 4HTMLDocument document = new HTMLDocument("https://httpbin.org/forms/post");
 5
 6// Create an instance of FormEditor
 7FormEditor editor = FormEditor.create(document, 0);
 8
 9// You can fill in the data using direct access to the input elements, like this:
10InputElement custname = editor.addInput("custname");
11custname.setValue("John Doe");
12
13document.save("out.html");
14
15// or this:
16TextAreaElement comments = editor.getElement(TextAreaElement.class, "comments");
17comments.setValue("MORE CHEESE PLEASE!");
18
19// or even by performing a bulk operation, like this one:
20java.util.Map<String, String> dictionary = new java.util.HashMap<>();
21dictionary.put("custemail", "john.doe@gmail.com");
22dictionary.put("custtel", "+1202-555-0290");
23
24// Create an instance of FormSubmitter
25FormSubmitter submitter = new FormSubmitter(editor);
26
27// Submit the form data to the remote server
28// If you need, you can specify user credentials and timeout for the request, etc.
29SubmissionResult result = submitter.submit();
30
31// Check the status of the result object
32if (result.isSuccess()) {
33    // Check whether the result is in json format
34    if (result.getResponseMessage().getHeaders().getContentType().getMediaType().equals("application/json")) {
35        // Print result data to console
36        System.out.println(result.getContent().readAsString());
37    } else {
38        // Load the result data as an HTML document
39        Document doc = result.loadDocument();
40        // Inspect HTML document here
41    }
42}

结论

Aspose.HTML for Java 库中的 FormEditor 和 FormSubmitter 类为以编程方式处理 HTML 表单提供了一种简化的方法。通过利用这些类,开发人员可以直接从其 Java 应用程序中高效地操作表单元素、填充数据和提交信息。

Aspose.HTML 提供免费的在线 转换器,用于将 HTML、XHTML、MHTML、EPUB、XML 和 Markdown 文件转换为各种流行格式。您可以轻松地将 HTML 转换为 PDFHTML 转换为 JPGSVG 转换为 PDFMHTML 转换为 PDFMD 转换为 HTML,只需选择文件,选择要转换的格式,就大功告成了。它速度快,而且完全免费!

文本 “免费在线转换器”