我在我的 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);
}
Run Code Online (Sandbox Code Playgroud)
默认情况下,对于 HTTP(S) 请求,curl_easy_perform()将执行一个GET请求,该请求检索所请求资源的标头和内容。由于您不需要该内容,HEAD因此应该发送一个请求,该请求将仅检索资源的标头而不是其内容。
CURLOPT_NOBODY为此目的使用该选项:
CURLOPT_NOBODY - 执行下载请求而不获取正文
设置为 1 的长参数告诉 libcurl 在执行下载操作时不要在输出中包含正文部分。对于 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);
}
Run Code Online (Sandbox Code Playgroud)