簡體   English   中英

CURL C++ 不退貨

[英]CURL C++ no return

我在我的 C++ 程序中使用 curl,它從網頁返回 HTML。 但我需要它只返回狀態碼。 我很確定返回內容的 function 稱為curl_easy_perform()

長話短說,我只需要它返回狀態碼而不是內容。

這是我的代碼。

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

默認情況下,對於 HTTP(S) 請求, curl_easy_perform()將執行GET請求,該請求檢索所請求資源的標頭和內容。 由於您不想要內容,因此您應該發送一個HEAD請求,該請求將僅檢索資源的標頭而不是其內容。

為此目的使用CURLOPT_NOBODY選項:

CURLOPT_NOBODY - 在不獲取正文的情況下執行下載請求

設置為 1 的長參數告訴 libcurl 在執行其他下載操作時不要在 output 中包含正文部分。 對於 HTTP(S),這會使 libcurl 執行 HEAD 請求。 對於大多數其他協議,這意味着只是不要求傳輸正文數據。

例如:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM