doujiang1939
doujiang1939
2016-10-02 07:38

JSoup登录网站并访问

已采纳

JSoup Login to website AND then open another page KEEPING that login session.

Could anyone explain how to log in on this website using JSoup?

Username:

Anything (E.G. 110000, 110001 and 110002 all work)

Password:

"sgl1617" (I don't care about someone knowing the password, you can't do anything with it.)

My code currently (Completely fails, I'm sure I'm on the wrong 'track'):

Connection.Response loginForm = Jsoup.connect("http://www.gymnasiumleiden.nl/roostersinfoweb/infoweb/index.php")
.method(Connection.Method.GET)
.execute();


Document doc = Jsoup.connect("http://www.gymnasiumleiden.nl/roostersinfoweb/infoweb/index.php").get();Jsoup.connect("http://www.gymnasiumleiden.nl/roostersinfoweb/infoweb/authentication.php")
.data("cookieexists", "false")
.data("username", "110638")
.data("password", "sgl1617")
.data("login", "Login")
.cookies(loginForm.cookies())
.post();

One thing I'm sure of: authentication.php doesn't exist.

I am new to JSoup, so please explain some code and tell me about the 'cookie' part (I know what cookies are, but not how you use them with JSoup.)

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

1条回答

  • doujiao4705 doujiao4705 5年前

    There are some points to correct:

    • the login endpoint is not correct (the correct one is http://www.gymnasiumleiden.nl/roostersinfoweb/infoweb/index.php);
    • some POST parameters you're sending are misspelled (e.g. username should be user);
    • some POST parameters are not required (e.g. cookieexists);
    • you're not adding the required csrf parameter in the POST request.
    • you should check the response to understand if login is ok or not.

    My working code (with an error checker):

    Connection.Response loginForm = Jsoup
      .connect("http://www.gymnasiumleiden.nl/roostersinfoweb/infoweb/index.php")
      .method(Connection.Method.GET)
      .execute();
    
    Document doc = loginForm.parse();
    String csrf = doc.select("input[name=csrf]").val();
    Connection.Response response = Jsoup.connect("http://www.gymnasiumleiden.nl/roostersinfoweb/infoweb/index.php")
            .data("user", "110638")
            .data("paswoord", "sgl1617")
            .data("login", "loginform")
            .data("csrf", csrf)
            .cookies(loginForm.cookies())
            .method(Connection.Method.POST)
            .execute();
    String body = response.body();
    if(body.contains("Wachtwoord is incorrect")){
        System.out.println("Password incorrect!");
    } else if(body.contains("Gebruikersnaam werd niet gevonden.")){
        System.out.println("Not found username!");
    } else {
        System.out.println("Login successfully!");          
    }
    
    点赞 评论 复制链接分享