How to properly send data via POSTFIELDS using CURL?
If you write the same code in Python, it will work and the site gives a response of 200, but in C++ it gives a response of 400. As I understand it, the problem is in postfields, although I could be wrong
#include <iostream>
#include <curl/curl.h>
size_t writeCallback(void* contents, size_t size, size_t nmemb, std::string* data) {
data->append((char*)contents, size * nmemb);
return size * nmemb;
}
int main() {
setlocale(LC_CTYPE, "ru_RU.UTF-8");
curl_global_init(CURL_GLOBAL_ALL);
CURL* curl;
CURLcode res;
std::string text;
struct curl_slist* list = NULL;
list = curl_slist_append(list, "X-Requested-With: XMLHttpRequest");
list = curl_slist_append(list, "Cookie: __ddg2_=0");
curl = curl_easy_init();
if (curl) {
curl_easy_setopt(curl, CURLOPT_COOKIEFILE, "");
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, writeCallback);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &text);
curl_easy_setopt(curl, CURLOPT_URL, "https://example.com");
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, list);
res = curl_easy_perform(curl);
if (res != CURLE_OK)
return 1;
std::string token = text.erase(0, text.find("<input type="hidden" name="_xfToken" value="") + 44);
token = token.erase(token.find("""), token.size());
text = "";
curl_easy_setopt(curl, CURLOPT_POST, 1);
curl_easy_setopt(curl, CURLOPT_COPYPOSTFIELDS, "_xfToken=" + token + "&server=ru&id=26");
res = curl_easy_perform(curl);
if (res != CURLE_OK)
return 2;
curl_easy_cleanup(curl);
}
curl_global_cleanup();
}
I tried using POSTFIELDS, COPYPOSTFIELDS and encoding data in it
New contributor
Sad0w is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.