For me the problem was that I didn't send the viewstate, eventvalidation, viewstategenerator values.
To get these values you have to first send a GET request to the login form page.
In my instance this was a default.aspx page.
Then you have to extract those values and put them into variables. Also of course you need the form login and password field ids, the submit button's id, among other things. For a list of all those variable that are sent, login manually and use chrome dev tools (inspect elements) to look at the network tab for a POST request. Inside it should show the username and password you submitted. There you will see other variables that are sent.
network tab in dev tools example
Next, send a POST request including all those variables, save the cookies from the response into a variable, and you can then use that to go to another page.
Code:
import java.io.IOException;
import java.util.Map;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.nodes.FormElement;
public class get_example {
public static void main(String[] args) throws IOException {
//===================================
Connection.Response response2 = Jsoup.connect("yourloginpage")
.method(Connection.Method.GET)
.execute();
Document responseDocument = response2.parse();
Element eventValidation = responseDocument.select("input[name=__EVENTVALIDATION]").first();
Element viewState = responseDocument.select("input[name=__VIEWSTATE]").first();
Element viewStateGen = responseDocument.select("input[name=__VIEWSTATEGENERATOR]").first();
Connection.Response response = Jsoup.connect("yourloginpage")
.method(Connection.Method.POST)
.data("ctl00$plnMain$txtLogin", "username")
.data("ctl00$plnMain$txtPassword", "password")
.data("ctl00$plnMain$Submit1", "Log In")
.data("ctl00$ucCopyright$hdnPrivacyStatement", "Privacy Statement")
.data("ctl00$ucCopyright$hdnTermsOfUse", "Terms of Use")
.data("__VIEWSTATE", viewState.attr("value"))
.data("__VIEWSTATEGENERATOR", viewStateGen.attr("value"))
.data("__EVENTVALIDATION", eventValidation.attr("value"))
.execute();
Map<String, String> cookies = response.cookies();
Document homePage = Jsoup.connect("anotherpage")
.cookies(cookies)
.get();
System.out.println(homePage.body().html());
}
}