ThatGuy343
ThatGuy343

Reputation: 2424

Jsoup, get value before executing form POST

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();

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..

Upvotes: 5

Views: 1892

Answers (2)

Sagar
Sagar

Reputation: 96

You would need to get the cookies form the GET call and add them in the subsequent POST call , so that session is maintained. Look at the solution from this post Getting Captcha image using jsoup

Upvotes: 0

Spectre
Spectre

Reputation: 658

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();

This would make two HTTP request (one each for the GET and the POST) each over there own connection.

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().

Upvotes: 2

Related Questions