gpt4 book ai didi

c++ - 如何发出 libcurl HTTP Web 请求?

转载 作者:行者123 更新时间:2023-11-30 17:03:01 24 4
gpt4 key购买 nike

我正在尝试从 url 获取 json 数据:

sub.domain.com/rest/getdiscounts?supermarketid=5323

我想获取从该 url 返回的数据。在终端中我可以这样做:

curl --user user:password "http://sub.domain.com/rest/getdiscounts?supermarketid=5323"

到目前为止我已经尝试了多种方法,例如:

static string lastResponse;

size_t server_response_stream(void *ptr, size_t size, size_t nmemb, void *)
{
lastResponse += (const char*)ptr;
return size * nmemb;
}

bool get_request(string data1, string& errorDescription)
{
CURL *curl = curl_easy_init();
if (curl == NULL)
{
errorDescription = "Unable to initialise Curl";
cout << errorDescription << std::endl;
return false;
}
const string url = "http://sub.domain.com/rest/";
curl_easy_setopt(curl, CURLOPT_URL, (url + "getdiscounts").c_str());
curl_easy_setopt(curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_easy_setopt(curl, CURLOPT_USERPWD, USPA);

char* dc1 = curl_easy_escape(curl, data1.c_str(), 0);
string arg = "supermarketid=" + (string)dc1;
const char* dt = arg.c_str();

curl_easy_setopt(curl, CURLOPT_POSTFIELDS, dt);
curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, (long)strlen(dt));

curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L);

lastResponse = "";
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, server_response_stream);

CURLcode res = curl_easy_perform(curl);

res = curl_easy_perform(curl);

if (res != CURLE_OK)
{
errorDescription = "Curl call to server failed!";
cout << errorDescription << std::endl;
return false;
}

curl_easy_cleanup(curl);
return true;
}

我用作来源this questionthis link

编辑:感谢您的帮助!我再次从头开始,现在可以正常工作了:

static string responseStr;
size_t write_callback(void *ptr, size_t size, size_t nmemb, void *)
{
responseStr = (const char*)ptr;
return size * nmemb;
}

string get_request()
{
CURL *curl;
CURLcode res;

curl = curl_easy_init();
if (curl)
{
curl_easy_setopt(curl, CURLOPT_URL, "http://sub.domain.com/rest/getdiscounts?supermarketid=5323");
curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
curl_easy_setopt(curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_easy_setopt(curl, CURLOPT_USERPWD, CREDENTIALS);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_callback);

res = curl_easy_perform(curl);

if (res != CURLE_OK)
{
cout << "curl_easy_perform() failed!" << std::endl;
curl_easy_strerror(res);
curl_easy_cleanup(curl);
return "";
}

else if (res == CURLE_OK)
{
curl_easy_cleanup(curl);
return responseStr;
}
}
}

最佳答案

CURLOPT_WRITEFUNCTION callback 的第一个参数 ptr函数server_response_stream,指向接收到的数据。该数据不是以 null 结尾的。

字符串+= operator必须接收一个指向空终止字符串的指针。

调用 lastResponse += (const char*)ptr; 导致未定义的行为。字节必须以不同的方式附加到字符串中。您可以使用参数 sizenmemb 逐个字符附加字符串来确定缓冲区的大小。

关于c++ - 如何发出 libcurl HTTP Web 请求?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36305340/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com