Jsoup Posting and Cookies: Maintaining a Session
When attempting to access subsequent pages on a website after logging in with jsoup, you may encounter difficulties due to the need for a cookie to maintain the session. While apache httpclient can handle this, there's an alternative solution within jsoup.
To resolve this issue:
Establish a Session and Retrieve the Cookie:
<code class="java">Connection.Response res = Jsoup.connect("http://www.example.com/login.php") .data("username", "myUsername", "password", "myPassword") .method(Method.POST) .execute(); String sessionId = res.cookie("SESSIONID"); // Determine the correct cookie name</code>
Send the Cookie on Subsequent Requests:
<code class="java">Document doc2 = Jsoup.connect("http://www.example.com/otherPage") .cookie("SESSIONID", sessionId) .get();</code>
By passing the sessionId cookie on subsequent requests, you can maintain the session and access other pages on the site. This allows you to scrape information successfully without relying on external libraries.
The above is the detailed content of How can I maintain a session with Jsoup after logging in to a website?. For more information, please follow other related articles on the PHP Chinese website!