當我從命令列運行curl --header <url here>時,我可以看到相當多的資訊,包括所需的欄位 Content-Length。
但是當我寫一個基于libcurl的C腳本時,包括這行
curl_easy_getinfo(c, CURLINFO_CONTENT_LENGTH_DOWNLOAD_T, &ContentLength);
ContentLength 的值最終為 -1,而我收到的標頭只是“HTTP/2 200”。
我似乎能夠從命令列 curl 獲取 Content-Length 欄位,但不使用 C 的 libcurl。是什么賦予了?
#include <stdlib.h>
#include <stdio.h>
#include <curl/curl.h>
int hcb(void *contents, size_t size, size_t nmemb, void *data) {
// this prints "HTTP/2 200"
printf("%.*s\n", (int)(size*nmemb), ((char *) contents));
return 0;
}
int wcb(void *contents, size_t size, size_t nmemb, void *data) {
printf("not implemented\n");
return 0;
}
ssize_t myfunc(){
char url[] = "http://thisisafakeurl.com/test.txt";
CURL *c = curl_easy_init();
if(c) {
CURLcode res;
curl_easy_setopt(c, CURLOPT_URL, url);
curl_easy_setopt(c, CURLOPT_HEADERFUNCTION, hcb);
curl_easy_setopt(c, CURLOPT_WRITEFUNCTION, wcb);
res = curl_easy_perform(c);
int ContentLength;
curl_easy_getinfo(c, CURLINFO_CONTENT_LENGTH_DOWNLOAD_T, &ContentLength);
// this line prints 23.
printf("content length: %i\n", ContentLength);
curl_easy_cleanup(c);
}
return 0;
}
int main() {
myfunc();
return 0;
}
uj5u.com熱心網友回復:
的檔案CURLOPT_HEADERFUNCTION說明以下內容:
此回呼函式必須回傳實際處理的位元組數。如果該數量與傳遞給您的函式的數量不同,它將向庫發出錯誤信號。這將導致傳輸中止,并且正在進行的 libcurl 函式將回傳
CURLE_WRITE_ERROR。
狀態的檔案CURLOPT_WRITEFUNCTION非常相似:
您的回呼應回傳實際處理的位元組數。如果該數量與傳遞給回呼函式的數量不同,它將向庫發出錯誤條件信號。這將導致傳輸中止并且使用的 libcurl 函式將回傳
CURLE_WRITE_ERROR。
由于您的回呼函式總是指示錯誤,根據參考的檔案,這將導致傳輸中止。這可能就是為什么這條線
curl_easy_getinfo(c, CURLINFO_CONTENT_LENGTH_DOWNLOAD_T, &ContentLength);
失敗了。
為了解決這個問題,您應該更改回呼函式以始終指示成功,方法是更改??行
return 0;
至
return nmemb;
在這兩個功能中。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/494863.html
