这是我用来提交表单的代码:
Connection.Response res = Jsoup.connect("http://example.com")
.data("id", "myID")
.data("username", "myUsername")
.data("code", "MyAuthcode") // get the value of Auth code from page element
.method(Method.POST).execute();
要成功提交给定的表单,需要为带有 [name="code"] 的字段设置一个值。
该值可以在页面上的另一个元素中找到。在实际提交如上所示的表单之前,我到底如何使用相同的连接获取元素的值?
我需要使用元素中的值才能成功填写表单。
Jsoup 实际上为每个请求打开一个新的 HTTP 连接,因此您的要求不太可能,但您可以接近:
// Define where to connect (doesn't actually connect)
Connection connection = Jsoup.connect("http://example.com");
// Connect to the server and get the page
Document doc = connection.get();
// Extract the value from the page
String authCode = doc.select("input[name='code']").val();
// Add the required data to the request
connection.data("id", "myID")
.data("username", "myUsername")
.data("code", authCode);
// Connect to the server and do a post
Connection.Response response = connection.method(Method.POST).execute();
这将在各自的连接上发出两个 HTTP 请求(GET 和 POST 各一个)。
如果您确实只想要一个连接,则必须使用不同的工具来连接到服务器(例如Apache-HTTP 客户端 http://hc.apache.org/httpcomponents-client-ga/index.html)。您仍然可以使用 jsoup 来解析您使用返回的内容Jsoup.parse()
.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)