SPOJ用Java登录

时间:2017-08-08 18:51:11

标签: java

我试图用Jsoup自动化Java中的SPOJ登录,但是响应页面不是我所期望的,下面是代码

public static void login() {
    try {
        Document doc;
        Connection.Response response;
        Map<String, String> cookies = new HashMap<>(), form = new HashMap<>();

        response = Jsoup.connect(LOGIN_URL) // http://spoj.com/login
                .method(Connection.Method.GET)
                .userAgent(USER_AGENT)
                .execute();

        cookies.putAll(response.cookies());
        form.put("login_user", LOGIN_ACCOUNT);
        form.put("password", LOGIN_PASSWORD);
        form.put("next_raw", "/");

        response = Jsoup.connect(LOGIN_URL)
                .cookies(cookies)
                .method(Connection.Method.POST)
                .data(form)
                .userAgent(USER_AGENT)
                .execute();

        System.out.println(response.body());
    } catch (IOException e) {

    }
}

响应正文结果仍然包含登录表单,这意味着我的登录尝试失败。有人可以帮忙吗?

1 个答案:

答案 0 :(得分:0)

我已经通过从标头中的set-cookie参数检索cookie并使用apache client更改登录实现来解决此问题

public static void login() {
    try {
        //Submit Login Form
        HttpResponse response = Request.Post(LOGIN_URL)
                .bodyForm(Form.form()
                        .add("login_user", ACCOUNT)
                        .add("password", PASSWORD)
                        .add("next_raw", "/")
                        .add("autologin", "1")
                        .build())
                .userAgent(USER_AGENT)
                .execute()
                .returnResponse();

        //Retrieve Cookie from Response
        StringBuilder sb = new StringBuilder();
        for(Header header : response.getAllHeaders()) {
            if(header.getName().equalsIgnoreCase("set-cookie") || header.getName().equalsIgnoreCase("set-cookie2")){
                sb.append(header.getValue()).append("; ");
            }
        }
        COOKIE = sb.toString();

        //Debugging to Verify if Login is Successful
        Document doc = Jsoup.connect(BASE_URL).cookies(cookieMapper()).get();
        System.out.println(doc.text());
    } catch (IOException e) {
        e.printStackTrace();
    }
}