C++ 使用libcurl发送post请求
我正在尝试通过CURL登录Twitter。 这是我的代码:C++ 使用libcurl发送post请求,c++,post,curl,C++,Post,Curl,我正在尝试通过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 = s
#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;
}
#包括
#包括
#包括
#包括
使用std::string;
大小写入数据(void*ptr、大小、大小nmemb、void*stream)
{
std::string buf=std::string(静态转换(ptr),大小*nmemb);
std::stringstream*响应=静态广播(流);
响应->写入(buf.c_str(),(std::streamsize)buf.size();
返回大小*nmemb;
}
int main(int argc,char*argv[])
{
std::字符串目标=”https://twitter.com/login";
卷曲*卷曲;
卷曲编码;
流响应;
char*data=“会话[用户名或电子邮件]=用户和会话[密码]=通过”;
struct curl_slist*chunk=NULL;
curl\u global\u init(curl\u global\u默认值);
curl=curl_easy_init();
if(curl){
curl_easy_setopt(curl,CURLOPT_URL,target.c_str());
curl\u easy\u setopt(curl,CURLOPT\u WRITEFUNCTION,write\u data);
curl_easy_setopt(curl,CURLOPT_VERBOSE,true);
curl_easy_setopt(curl、CURLOPT_WRITEDATA和response);
curl_easy_setopt(curl,CURLOPT_USERAGENT,“Mozilla/4.0(兼容;MSIE 6.0;Windows NT 5.1;SV1;.NET CLR 1.0.3705;.NET CLR 1.1.4322)”;
curl\u easy\u setopt(curl,CURLOPT\u SSL\u VERIFYPEER,false);
curl_easy_setopt(curl,CURLOPT_FOLLOWLOCATION,true);
curl_easy_setopt(curl,CURLOPT_POSTFIELDS,data);
res=旋度(curl)\u容易执行(curl);
旋度\轻松\清洁(旋度);
curl_global_cleanup();
}
我建议您的请求(正确地)被识别为来自程序而非人类,因此被拒绝
这将是一个从“真实”(ie浏览器)会话中捕获所有正确的标题和cookie的问题……但实际上,我认为您最好使用Twitter api,因为这就是它的设计目的。非常感谢!!我在Chrome中查看了网络并复制了标题。