102

How do I get the HTTP status code (eg 200 or 500) after calling curl_easy_perform?

Raedwald
  • 46,613
  • 43
  • 151
  • 237
twk
  • 16,760
  • 23
  • 73
  • 97

2 Answers2

153

http://curl.haxx.se/libcurl/c/curl_easy_getinfo.html

CURLINFO_RESPONSE_CODE

Pass a pointer to a long to receive the last received HTTP or FTP code. This
option was known as CURLINFO_HTTP_CODE in libcurl 7.10.7 and earlier. This 
will be zero if no server response code has been received. Note that a 
proxy's CONNECT response should be read with CURLINFO_HTTP_CONNECTCODE 
and not this. 
curl_code = curl_easy_perform (session);
long http_code = 0;
curl_easy_getinfo (session, CURLINFO_RESPONSE_CODE, &http_code);
if (http_code == 200 && curl_code != CURLE_ABORTED_BY_CALLBACK)
{
         //Succeeded
}
else
{
         //Failed
}
Vinko Vrsalovic
  • 330,807
  • 53
  • 334
  • 373
13

The other answer is absolutely correct, but I would also like to add that it might not be wise to check the error code by hand, the 200 code is not the only code that signifies success.

I'd recoment using the libcurl option CURLOPT_FAILONERROR that when activated will make libcurl consider 400 and 500 -category statuses a request failure and will not return CURLE_OK from perform.

kralyk
  • 4,249
  • 1
  • 32
  • 34
  • 1
    As an extension to this, depending on the options set, there are other non "200 series" codes that are a success, albeit with the understanding that more work is necessary, Two of the best known being 301 and 302. Certainly curl can be set up to handle these automatically, but there may be cases where the application might want to handle them itself. One possibility might be when https:// is in use with client authentication, and a completely new certificate chain is needed for the target of the 301 / 302 result. – dgnuff Jan 13 '19 at 01:55
  • What is the problem to just check manually if status code is < 400? – ScienceDiscoverer Aug 27 '23 at 04:50