简体   繁体   中英

JSOUP Automatically Login to a website

I am trying to parse a website which requires login. From browser, when I do login at the login page( https://backoffice.holidayinsider.com/backoffice2/login ), I am automatically redirected to https://backoffice.holidayinsider.com/backoffice2/login .

So first of all I am trying to automate the login using Java. My approach is motivated by this stackoverflow response . The code I am using is the following:

package Login;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import java.io.IOException;
import java.util.Map;
public class DoLogin {
    public static void main(String[] args)
    {

        try {

            Connection.Response loginForm = Jsoup.connect("https://backoffice.holidayinsider.com/backoffice2/login")
                .method(Connection.Method.GET)
                .execute();

            Connection.Response mainPage = Jsoup.connect("https://backoffice.holidayinsider.com/backoffice2")
                .data("username", "myusername")
                .data("password", "mypass")
                .cookies(loginForm.cookies()).execute();
            System.out.println(mainPage.parse());

            Map<String, String> cookies = mainPage.cookies();

            Document evaluationPage = Jsoup.connect("https://backoffice.holidayinsider.com/backoffice2/")
                .cookies(cookies)
                .execute().parse();
            System.out.println(evaluationPage);


        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

It seems the login is working as status code is 200. Now the problem is when I print mainPage, it seems it is still at login page. What can be the reason? Thank you in advance for any help or suggestion.

While your login you need to add POST method :

        Connection.Response loginForm = Jsoup.connect("https://backoffice.holidayinsider.com/backoffice2/login")
            .method(Connection.Method.GET)
            .execute(); 

        Connection.Response mainPage = Jsoup.connect("https://backoffice.holidayinsider.com/backoffice2/login")
            .data("username", "myusername") 
            .data("password", "mypass") 
            .cookies(loginForm.cookies())
            .followRedirects(true)
            .method(Connection.Method.POST).execute(); 
        System.out.println(mainPage.parse());

        Map<String, String> cookies = mainPage.cookies();

        Document evaluationPage = Jsoup.connect("https://backoffice.holidayinsider.com/backoffice2/")
            .cookies(cookies)
            .get();
        System.out.println(evaluationPage);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM