温馨提示×

c++ post请求如何设置超时

c++
小樊
163
2024-07-15 23:42:48
栏目: 编程语言
C++开发者专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

在C++中,可以使用curl库来发送HTTP请求并设置超时时间。以下是一个示例代码:

#include <curl/curl.h>

int main() {
    CURL *curl;
    CURLcode res;

    curl = curl_easy_init();
    if(curl) {
        curl_easy_setopt(curl, CURLOPT_URL, "http://example.com");
        curl_easy_setopt(curl, CURLOPT_TIMEOUT, 10); // 设置超时时间为10秒

        res = curl_easy_perform(curl);
        if(res != CURLE_OK) {
            fprintf(stderr, "curl_easy_perform() failed: %s\n", curl_easy_strerror(res));
        }

        curl_easy_cleanup(curl);
    }

    return 0;
}

在上面的示例代码中,使用curl_easy_setopt函数来设置超时时间为10秒,可以根据实际需求调整超时时间。最后调用curl_easy_perform函数来执行HTTP请求。如果请求超时或失败,将会在标准错误流中输出错误信息。

请确保在编译时链接curl库,例如使用以下命令编译代码:

g++ example.cpp -o example -lcurl

亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读:c++ post请求有哪些常见错误

0