c++

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

小樊
109
2024-07-15 23:42:48
栏目: 编程语言

在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

0
看了该问题的人还看了