Jsoup,在执行表单POST之前获取值

这是我用来提交表单的代码:

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 – HTTPClient )。 您仍然可以使用jsoup来解析使用Jsoup.parse()

您需要从GET调用中获取cookie并在随后的POST调用中添加它们,以便维护会话。 看看这篇文章使用jsoup获取validation码图像的解决方案