libcurl忽略正文,以防HTTP不能通过

问题描述 投票:0回答:1

我通常使用curl下载文件。但是,服务器做了一件棘手的事情:它返回非200码并且仍然发送一些数据。问题是写入数据后我拥有HTTP代码,但是如果非200,我不想写任何东西。有谁知道一种无需在磁盘或内存上存储数据的方法?

curl_easy_setopt(curl, CURLOPT_URL, url);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, curlWriteHandler);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, ptr);
res = curl_easy_perform(curl);
if (res == CURLE_OK) {
    return 0;
}

long response_code;
curl_easy_getinfo(curl_.get(), CURLINFO_RESPONSE_CODE, &response_code);
if (response_code != 200) {
    return 0;
}

size_t curlWriteHandler(char* chars, size_t size, size_t nmemb, void* userp) {
    // write to file

    return size * nmemb;
}
c curl libcurl
1个回答
0
投票

设置CURLOPT_FAILONERROR应对4xx和5xx错误。

使用此选项并检测到错误时,将导致连接关闭并返回CURLE_HTTP_RETURNED_ERROR。

curl_easy_setopt(curl, CURLOPT_FAILONERROR, 1L);
© www.soinside.com 2019 - 2024. All rights reserved.