LibCURL 登录网站

LibCURL login to website

所以我知道还有其他类似的问题,我也一直在阅读这些问题,但我认为我的问题是独一无二的。我正在尝试登录 mojang.com(不要询问)并在后续请求中保持登录状态。但是当我向登录页面发送 POST 请求时,它只是将登录页面转储给我。我怎样才能通过登录页面?

我相信我已经激活了 cookie 引擎并且 cookie 被成功记录和打印但可能没有被使用?

我的目标是登录成功后访问这个页面:https://account.mojang.com/me

session* mojang_login(const char *user, const char *pass,
        const char *q1, const char *q2, const char *q3)
{
    const char *url = "https://account.mojang.com/login";
    const char *payload = construct_payload(user, pass);
    const char *ua =
        "Mozilla/5.0 (X11; Linux x86_64; rv:55.0) Gecko/20100101 Firefox/55.0";
    char errbuf[CURL_ERROR_SIZE] = {0};

    CURL *curl;
    CURLcode res;

    curl = curl_easy_init();

    if (!curl)
    {
        fprintf(stderr, "Failed to initialize curl\n");
        return NULL;
    }

    curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L);
    curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, errbuf);
    curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
    curl_easy_setopt(curl, CURLOPT_URL, url);
    curl_easy_setopt(curl, CURLOPT_USERAGENT, ua);
    curl_easy_setopt(curl, CURLOPT_COOKIEFILE, "");
    curl_easy_setopt(curl, CURLOPT_POST, 1L);
    curl_easy_setopt(curl, CURLOPT_POSTFIELDS, payload);
    res = curl_easy_perform(curl);
    free((void*) payload);

    if (res != CURLE_OK)
    {
        curl_err(res, errbuf);
        return NULL;
    }

    struct curl_slist *cookies;
    res = curl_easy_getinfo(curl, CURLINFO_COOKIELIST, &cookies);

    if (res != CURLE_OK)
    {
        curl_err(res, errbuf);
        return NULL;
    }

    while (cookies)
    {
        printf("\nCOOKIE DATA: %s\n", cookies->data);
        cookies = cookies->next;
    }

    session *s1 = NULL; /* safe_malloc(sizeof(session));*/

    curl_easy_cleanup(curl);
    return s1;
}

(因为你实际上并没有提供完整的源代码,所以我不能准确地告诉你,但我会用通用术语来谈论这个问题)

首先,您需要确保在登录前足够长的时间记录 cookies-POST。有些网站会在您查看登录页面时设置 cookie,因此您可能需要先获取它。

然后,您需要确保在登录时像浏览器一样提交所有内容(包括那些您在浏览器视图中看不到的隐藏表单字段)。解决这个问题的一个好方法是使用浏览器的网络工具来准确捕获浏览器发送的内容,然后确保您的代码发送相同的内容。然后您可以迭代几次以确保您的请求与浏览器的请求尽可能相似。

当然,您必须启用 cookie,并且必须遵循重定向,因为大多数登录都会将您带到另一个页面。