溫馨提示×

c++ post請求如何設置超時

c++
小樊
209
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
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女