在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