Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

CURL C++ no return

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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);
}

>Solution :

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);
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading