我花了好几天时间试图解决这个问题,但运气不佳。 我可以登录其他网站,但不能登录 Twitter,这让我抓狂!
我不会发布我的整个程序,只发布重要的部分。 (为了大家的方便,我会抽象出一些部分)
int main(int argc, const char * argv[]) {
curl_global_init( CURL_GLOBAL_ALL );
CURL * myHandle = curl_easy_init ( );
CURLcode result;
OutputBuffer output;
/* Fetch Login page to parse authenticity token */
// Set up a couple initial paramaters that we will not need to mofiy later.
curl_easy_setopt(myHandle, CURLOPT_USERAGENT, "Mozilla/4.0");
curl_easy_setopt(myHandle, CURLOPT_AUTOREFERER, 1 );
curl_easy_setopt(myHandle, CURLOPT_FOLLOWLOCATION, 1 );
curl_easy_setopt(myHandle, CURLOPT_WRITEFUNCTION, WriteMemoryCallback);
curl_easy_setopt(myHandle, CURLOPT_WRITEDATA, &output);
curl_easy_setopt(myHandle, CURLOPT_COOKIEFILE, "cookies.txt");
curl_easy_setopt(myHandle, CURLOPT_COOKIEJAR, "cookies.txt");
// Visit the login page once to obtain a PHPSESSID cookie
curl_easy_setopt(myHandle, CURLOPT_URL, "https://www.twitter.com/login/");
result = curl_easy_perform( myHandle );
// assume that the program properly retrieves the authenticity token here and stores it in 'token'
// then creates 'char *postreq' with the following format:
// session[username_or_email]=EnterUsername&session[password]=EnterPassword&remember_me=1&return_to_ssl=true&scribe_log=&redirect_after_login=true&authenticity_token=TokenGoesHere&ui_metrics=off&ui_metrics_seed=1450307791003
/*********************************************************************************************************/
// perform login
// set the post fields
curl_easy_setopt(myHandle, CURLOPT_COPYPOSTFIELDS, postreq);
// forge the HTTP referer field, or HTS will deny the login
curl_easy_setopt(myHandle, CURLOPT_REFERER, "https://www.twitter.com/login/sessions");
result = curl_easy_perform( myHandle );
printf("%s", output.buffer);
return 0;
}
我知道它失败了,因为我打印出生成的网页并通过关键字“注销”(它只应在登录时出现)进行过滤,但从未找到它。 我不知道我做错了什么。它适用于其他网站:/
请不要告诉我使用 Twitter API! 我非常想使用 C 和 libcurl w/out API 来做到这一点。
到目前为止我的逻辑: 阶段1: - 获取登录页面 - 解析真实性 token - 将 session cookie 保存到文件
第 2 阶段: - 构建 POST 请求:session[username_or_email]=EnterUsername&session[password]=EnterPassword&authenticity_token=TokenGoesHere - 从文件加载 cookie - 执行登录
我到处都找了,没搞明白。 非常感谢任何指导!
附言。我的 POST 请求格式是否适用于 Twitter?还是遗漏了什么?
最佳答案
首先,我认为您将 POST 发送到错误的 URL(请参阅表单标记的 action=""参数)。然后我还认为您应该避免关闭/重新创建简易句柄,因为那只是额外的开销。
但更笼统地说:在您的浏览器(Firefox 或 Chrome)中启动您的网络工具,并记录当您手动转到该页面然后登录时它做了什么。您特别检查登录表单页面的 GET 和浏览器登录的 POST。
然后您利用这些知识并仔细检查您的使用 libcurl 的应用程序是否以相同的方式工作。然后使用 DEBUGFUNCTION 会很有用全面跟踪 libcurl 发送和接收的所有内容,以便您可以检查它是否与浏览器的操作非常相似。
关于c - 使用 C libcurl 库登录 Twitter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34306221/