问题描述
这是我用来提交表单的代码:
Here is code i am using to submit a form:
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"]的字段需要设置一个值.
To submit the given form successfully, the field with [name="code"] needs to have a value set.
该值可以在页面上的另一个元素中找到.在实际提交如上所示的表单之前,如何使用相同的连接获取元素的值?
The value can be found on the page in another element. How on earth do I get the value of an element using the same connection, before actually submitting the form as shown above?
我需要使用元素中的值,才能成功填写表单.
I need to use a value from an element, to fill out the form successfully..
推荐答案
Jsoup实际上为每个请求打开了一个新的HTTP连接,因此您的询问不太可能,但是您可以关闭:
Jsoup actually opens a new HTTP connection for each request so what your asking isn't quite possible but you can get close:
// 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).
This would make two HTTP request (one each for the GET and the POST) each over there own connection.
如果您确实只想要一个连接,则必须使用其他工具连接到服务器(例如 Apache-HTTPClient ).您仍然可以使用jsoup来解析使用Jsoup.parse()
返回的内容.
If you really want only one connection you'll have to use a different tool for connecting to the server (eg. Apache - HTTPClient). You would still be able to use jsoup to parse what you get back using Jsoup.parse()
.
这篇关于Jsoup,在执行表单POST之前获取值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!