使用 libcurl 发送 post 请求

Sending post request with libcurl

我正在尝试通过 CURL 登录 Twitter。 这是我的代码:

#include <iostream>
#include <string>
#include <curl\curl.h>
#include <sstream>

using std::string;

size_t write_data(void *ptr, size_t size, size_t nmemb, void *stream)
{
    std::string buf = std::string(static_cast<char *>(ptr), size * nmemb);
    std::stringstream *response = static_cast<std::stringstream *>(stream);
    response->write(buf.c_str(), (std::streamsize)buf.size());
    return size * nmemb;
}

int main(int argc, char*argv[])
{
    std::string target = "https://twitter.com/login";
    CURL *curl;
    CURLcode res;
    std::stringstream response;
    char* data = "session[username_or_email]=user&session[password]=pass";
    struct curl_slist *chunk = NULL;
    curl_global_init(CURL_GLOBAL_DEFAULT);
    curl = curl_easy_init();
    if (curl) {

        curl_easy_setopt(curl, CURLOPT_URL, target.c_str());
        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data);
        curl_easy_setopt(curl, CURLOPT_VERBOSE, true);
        curl_easy_setopt(curl, CURLOPT_WRITEDATA, &response);
        curl_easy_setopt(curl, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.0.3705; .NET CLR 1.1.4322)");
        curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, true);
        curl_easy_setopt(curl, CURLOPT_POSTFIELDS, data);
        res = curl_easy_perform(curl);

        curl_easy_cleanup(curl);
        curl_global_cleanup();
    }
    std::cout << response.str() << std::endl;
    cin.ignore();
    return 0;
}

我收到这条消息:

403 Forbidden: The server understood the request, but is refusing to fulfill it

我该怎么办?

我建议您的请求被(正确地)识别为来自非人类程序,因此被拒绝。

这将是从 "real"(即浏览器)session 中捕获所有正确的 headers 和 cookie 的问题......但实际上,我认为你会最好使用 Twitter api,因为它就是为此而设计的。