gpt4 book ai didi

c++ - CURL 执行完毕超时

转载 作者:行者123 更新时间:2023-11-30 04:03:46 25 4
gpt4 key购买 nike

我正在使用 C++ 中的 curl 执行服务器请求,它以片段形式返回响应,这些片段的大小也可能会有所不同。

每 block 到达时,回调函数正在被调用。问题是我无法检测连接何时完成以便对我的父类执行另一个回调。

顺便说一下,我想知道我们是否可以设置和检测 curl 的超时?

这是我的简短代码:

CURL *curl = curl_easy_init();
curl_global_init(CURL_GLOBAL_ALL);

curl_easy_setopt(curl, CURLOPT_URL, "My URL");
curl_easy_setopt(curl, CURLOPT_POST, 1);
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, "My Postfields");
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, writeCallback);

curl_easy_perform(curl);
curl_easy_cleanup(curl);
curl_global_cleanup();

默认回调:

size_t writeCallback(char* buf, size_t size, size_t nmemb, void* up)
{
//do something
//But how can I detect the last callback when connection finished
//in order to call an another one?
return size*nmemb;
}

最佳答案

您需要的数据可以在回调期间保存下来,然后在 curl_easy_perform 返回时使用。示例:

CURL *curl = curl_easy_init();
curl_global_init(CURL_GLOBAL_ALL);

// NOTE: added to accumulate data.
std::string result;

curl_easy_setopt(curl, CURLOPT_URL, "My URL");
curl_easy_setopt(curl, CURLOPT_POST, 1);
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, "My Postfields");
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, writeCallback);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &result); // NOTE: added
curl_easy_perform(curl);

// TODO: do something with your data stored in result

curl_easy_cleanup(curl);
curl_global_cleanup();

在你的写回调中:

size_t writeCallback(char* buf, size_t size, size_t nmemb, void* up)
{
std::string* pstr = static_cast<std::string*>(up);
std::copy(buf, buf+size*nmemb, std::back_inserter(*pstr));
return size*nmemb;
}

或类似的东西。我将所有错误检查留给您(对于任何拼写错误,我深表歉意;我没有立即可用的编译器来验证它)。

关于超时长度,有多种超时选项可用于简单模式的 curl 请求。事实上,太多了,无法在这里提及。请参阅 curl_easy_setopt 的文档,特别是页面下方大约 2/3 处的连接选项。

祝你好运。

关于c++ - CURL 执行完毕超时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24201602/

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