【问题标题】:Sending post request with libcurl使用 libcurl 发送 post 请求
【发布时间】:2015-02-28 01:47:15
【问题描述】:

我正在尝试通过 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:服务器理解请求,但拒绝 实现它

我该怎么办?

【问题讨论】:

    标签: c++ post curl


    【解决方案1】:

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

    这将是从“真实”(即浏览器)会话中捕获所有正确的标头和 cookie 的问题...但实际上,我认为您最好使用 Twitter api,因为这就是它专为。

    【讨论】:

    • 非常感谢!!我在 Chrome 中查看了网络并复制了标头。
    猜你喜欢
    • 1970-01-01
    • 2011-05-13
    • 1970-01-01
    • 2023-01-13
    • 2013-09-24
    • 2013-10-06
    • 2017-02-13
    • 2021-11-30
    • 2017-05-03
    相关资源
    最近更新 更多