使用libcurl的Http状态代码?

twk*_*twk 88 c http libcurl

在调用curl_easy_perform后如何获取HTTP状态代码(例如200或500)?

Vin*_*vic 132

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
}
Run Code Online (Sandbox Code Playgroud)


kra*_*lyk 10

另一个答案是绝对正确的,但我还想补充一点,手动检查错误代码可能并不明智,该200代码并不是唯一表示成功的代码。

我建议使用 libcurl 选项CURLOPT_FAILONERROR,激活后将使 libcurl 考虑400500-category 状态为请求失败,并且不会CURLE_OK从执行返回。