I'm using curl in my C program, and it is returning the HTML from the webpage. But I need it to only return the status code. I'm pretty sure the function that's returning the contents is called curl_easy_perform()
.
Long story short, I just need it to return the status code and not the content.
Here is my code.
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);
}
CodePudding user response:
By default, for an HTTP(S) request, curl_easy_perform()
will perform a GET
request, which retrieves the requested resource's headers and content. Since you don't want the content, you should send a HEAD
request instead, which will retrieve only the resource's headers and not its content.
Use the CURLOPT_NOBODY
option for this purpose:
CURLOPT_NOBODY - do the download request without getting the body
A long parameter set to 1 tells libcurl to not include the body-part in the output when doing what would otherwise be a download. For HTTP(S), this makes libcurl do a HEAD request. For most other protocols it means just not asking to transfer the body data.
For example:
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);
}