我正在尝试使用 libcurl 将 POST 请求从 Python 移植到 C++,但我无法使用收到的 json 数据。
Python 运行起来轻而易举,我可以从响应中提取任何相关数据。在 C++ 中,我得到了一些二进制数据,但我无法使用它。
nlohmann::json::parse(...)
但没有成功。Python代码:
import requests
url = 'https://example.com'
headers= {
'accept-encoding': 'gzip, deflate, br',
'cache-control': 'no-cache',
'connection': 'Keep-Alive',
'content-type': 'application/json',
'version': '4.9.0'
}
loginData = {"email": "xxx", "password": "yyy"}
r = requests.post(url=url , headers=headers, json=loginData)
print(r.json())
C++代码:
#include <iostream>
#include <curl/curl.h>
static size_t WriteCallback(void *contents, size_t size, size_t nmemb, void *userp)
{
((std::string *)userp)->append((char *)contents, size * nmemb);
return size * nmemb;
}
int main(int argc, char *argv[])
{
// Init
CURL *curl;
CURLcode res;
curl = curl_easy_init();
if (curl)
{
curl_easy_setopt(curl, CURLOPT_VERBOSE, 1);
curl_easy_setopt(curl, CURLOPT_POST, 1L);
// URL
std::string url = "https://example.com";
curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
// Header
struct curl_slist *header = NULL;
header = curl_slist_append(header, "accept-encoding: gzip, deflate, br");
header = curl_slist_append(header, "cache-control: no-cache");
header = curl_slist_append(header, "connection: Keep-Alive");
header = curl_slist_append(header, "content-type: application/json");
header = curl_slist_append(header, "version: 4.9.0");
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, header);
// Post fields
std::string jsonStr = R"({"email":"xxx", "password":"yyy"})";
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, jsonStr.c_str());
// Write
std::string buffer = "";
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &buffer);
// Run
res = curl_easy_perform(curl);
if (res != CURLE_OK)
{
std::cout << "Error : " << res << std::endl;
std::cout << curl_easy_strerror(res) << std::endl;
curl_easy_cleanup(curl);
curl_slist_free_all(header);
return 1;
}
else
std::cout << "Received : " << buffer << std::endl;
curl_easy_cleanup(curl);
curl_slist_free_all(header);
}
return 0;
}
谢谢你伊戈尔
通过切换编码,我能够得到纯文本响应。其中提到我被阻止了。
事实证明,服务器正在等待用户代理,我补充道:
header = curl_slist_append(header, "user-agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/111.0.0.0 Safari/537.36");