我将libcurl用于RESTful库。我在PUT消息中遇到两个问题,我只是想通过put发送一个像“hello”这样的小内容。
当我按照curl.haxx.se上的手册并且返回0表示我已经完成了内容时,PUT的块的READFUNCTION会花费很长时间(分钟)。 (在os X上)当我返回一些&gt; 0这成功得快得多(<1秒)
当我在我的linux机器上运行它(ubuntu 10.4)时,这个阻塞事件在我返回0时似乎永远不会返回,如果我改变行为以返回写入的大小libcurl会附加http体内发送的所有数据方式更多的数据,它失败了来自服务器的“太多数据”消息。我的readfunction在下面,任何帮助将不胜感激。 我正在使用libcurl 7.20.1
typedef struct{
void *data;
int body_size;
int bytes_remaining;
int bytes_written;
} postdata;
size_t readfunc(void *ptr, size_t size, size_t nmemb, void *stream) {
if(stream) {
postdata *ud = (postdata*)stream;
if(ud->bytes_remaining) {
if(ud->body_size > size*nmemb) {
memcpy(ptr, ud->data+ud->bytes_written, size*nmemb);
ud->bytes_written+=size+nmemb;
ud->bytes_remaining = ud->body_size-size*nmemb;
return size*nmemb;
} else {
memcpy(ptr, ud->data+ud->bytes_written, ud->bytes_remaining);
ud->bytes_remaining=0;
return 0;
}
}
答案 0 :(得分:0)
来自联机帮助页(man curl_easy_setopt):
CURLOPT_READFUNCTION
Function pointer that should match the following prototype: size_t function( void *ptr, size_t size, size_t nmemb, void *stream); This function gets called by libcurl as soon as
it needs to read data in order to send it to the peer. The data area pointed at by the pointer ptr may be filled with at most size multiplied with nmemb number of bytes. Your
function must return the actual number of bytes that you stored in that memory area. Returning 0 will signal end-of-file to the library and cause it to stop the current trans-
fer.
If you stop the current transfer by returning 0 "pre-maturely" (i.e before the server expected it, like when you've told you will upload N bytes and you upload less than N
bytes), you may experience that the server "hangs" waiting for the rest of the data that won't come.
The read callback may return CURL_READFUNC_ABORT to stop the current operation immediately, resulting in a CURLE_ABORTED_BY_CALLBACK error code from the transfer (Added in
7.12.1)
If you set the callback pointer to NULL, or doesn't set it at all, the default internal read function will be used. It is simply doing an fread() on the FILE * stream set with
CURLOPT_READDATA.
因此返回CURL_READFUNC_ABORT以停止操作