简体   繁体   中英

libcurl: curl_easy_perform blocks unless CURLOPT_READFUNCTION is set

I am trying to use libcurl C++ to make REST/HTTP requests. I noticed curl_easy_perform blocks but if I set CURLOPT_READFUNCTION it doesn't. I just want to understand why that is, I am new to libcurl or HTTP/REST protocol.

Here is the code:

m_pCurl = curl_easy_init();
curl_easy_setopt(m_pCurl, CURLOPT_URL, "https://blahblahblah/api/auth/user/login");      
curl_easy_setopt(m_pCurl, CURLOPT_VERBOSE, 1L);
curl_easy_setopt(m_pCurl, CURLOPT_POST, 1);
curl_easy_setopt(m_pCurl, CURLOPT_COOKIE, "SKEY=BLAHBLAHBLAH");

struct curl_slist *list = NULL;

list = curl_slist_append(list, "Accept: application/json");
list = curl_slist_append(list, "Connection: keep-alive");
list = curl_slist_append(list, "Expect:");
list = curl_slist_append(list, "Content-Type: application/json");
list = curl_slist_append(list, "x-website-parameters: LALALALA");
curl_easy_setopt(m_pCurl, CURLOPT_HTTPHEADER, list);

// Callbacks
readarg_t rarg;

// readcb is a callback function
// Removing the two lines below will cause curl_easy_perform to hang
curl_easy_setopt(m_pCurl, CURLOPT_READFUNCTION, readcb);
curl_easy_setopt(m_pCurl, CURLOPT_READDATA, &rarg);

CURLcode res = curl_easy_perform(m_pCurl);

Note: Some of the encoded data are changed above.

Any help would be greatly appreciated.

Thanks, K

According to The Manual ...

CURLOPT_READFUNCTION explained

...

If you set this callback pointer to NULL, or don't set it at all, the default internal read function will be used. It is doing an fread() on the FILE * userdata set with CURLOPT_READDATA.

However you also don't set CURLOPT_READDATA . So looking again at The manual ...

CURLOPT_READDATA explained

...

By default, this is a FILE * to stdin.

So the reason your program "hangs" appears to be because it is waiting for something to arrive on the standard input stdin .

So the way it is supposed to work is this.

1) If you do nothing the data sent to the server comes from the standard input (which is often the keyboard).

2) If you set only CURLOPT_READDATA then it must be a FILE* you opened to an input file that contains the data you want to send.

3) If you set CURLOPT_READFUNCTION then CURLOPT_READDATA can point to anything your function needs to fulfil its task of sending data to the server.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM