CURL C++ no return

CURL C++ no return

本文关键字:return no C++ CURL      更新时间:2024-09-26

我在C++程序中使用curl,它从网页返回HTML。但我需要它只返回状态代码。我确信返回内容的函数叫做curl_easy_perform()

长话短说,我只需要它返回状态代码,而不是内容。

这是我的密码。

CURL *curl = curl_easy_init();
if(curl) {
CURLcode res;
curl_easy_setopt(curl, CURLOPT_URL, "example.com");
res = curl_easy_perform(curl);
if(res == CURLE_OK) {
long response_code;
curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &response_code);
}
curl_easy_cleanup(curl);
}

默认情况下,对于HTTP(S(请求,curl_easy_perform()将执行GET请求,该请求检索所请求资源的标头和内容。由于您不需要内容,因此应该发送HEAD请求,该请求将只检索资源的标头,而不检索其内容。

为此使用CURLOPT_NOBODY选项:

CURLOPT_NOBODY-在不获取正文的情况下进行下载请求

设置为1的长参数告诉libcurl在进行下载时不要在输出中包含body部分对于HTTP(S(,这使得libcurl执行HEAD请求对于大多数其他协议,这意味着不要求传输身体数据。

例如:

CURL *curl = curl_easy_init();
if(curl) {
CURLcode res;
curl_easy_setopt(curl, CURLOPT_URL, "example.com");
curl_easy_setopt(curl, CURLOPT_NOBODY, 1); // <-- ADD THIS
res = curl_easy_perform(curl);
if(res == CURLE_OK) {
long response_code;
curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &response_code);
}
curl_easy_cleanup(curl);
}