curllib库http chunk发送方法纠错
以前一直以为发送chunk数据只要http协议的头部添加
Transfer-Encoding: chunked
上面的错误是:
设置了CURLOPT_POSTFIELDS,CURLOPT_POSTFIELDSIZE这两选项
这样设置后就不是采用chunk发送了,而是采用普通方式
这样发送,服务器就可以收到了。
另外感觉上面的回掉写得很巧啊。
参考:
curl库中的例子post-callback.c
http://hi.baidu.com/zhujinyu/blog/item/464522f42f634664dcc4747b.html
http://blog.sina.com.cn/s/blog_78cf66b10100rvuw.html
http://blog.chinaunix.net/link.php?url=http://curl.haxx.se%2Flibcurl%2Fc%2Fcurl_easy_setopt.html%23CURLOPTREADDATA
以前一直以为发送chunk数据只要http协议的头部添加
Transfer-Encoding: chunked
就可以了,所以写了下面错误的代码
static int send_request(const char *req, char **data, int req_length)
{
struct curl_slist *phttp_headers = NULL;
CURL* ins_curl = NULL;
//make_http_headers(&phttp_headers);
ins_curl = curl_easy_init();
if (ins_curl == NULL)
{
printf("init curl failed\n");
return -1;
}
phttp_headers = curl_slist_append(phttp_headers, "Transfer-Encoding: chunked");
curl_slist_append(phttp_headers, "Content-Encoding: gzip");
curl_easy_setopt(ins_curl, CURLOPT_URL, DEFAULT_SERVER);
curl_easy_setopt(ins_curl, CURLOPT_WRITEFUNCTION, read_response_data);
curl_easy_setopt(ins_curl, CURLOPT_POST, 1L);
curl_easy_setopt(ins_curl, CURLOPT_VERBOSE, 1L);
curl_easy_setopt(ins_curl, CURLOPT_HEADER, 1L);
curl_easy_setopt(ins_curl, CURLOPT_FOLLOWLOCATION, 1L);
// setup chunk and post data
curl_easy_setopt(ins_curl, CURLOPT_HTTPHEADER, phttp_headers);
curl_easy_setopt(ins_curl, CURLOPT_POSTFIELDS, req);
curl_easy_setopt(ins_curl, CURLOPT_POSTFIELDSIZE, req_length);
if(curl_easy_perform(ins_curl) != CURLE_OK)
{
printf("http transform error\n");
}
curl_easy_cleanup(ins_curl);
return 1;
}
上面的错误是:
设置了CURLOPT_POSTFIELDS,CURLOPT_POSTFIELDSIZE这两选项
这样设置后就不是采用chunk发送了,而是采用普通方式
所以参考了curl库的例子
设置CURLOPT_READFUNCTION,CURLOPT_READDATA
/* we want to use our own read function */
curl_easy_setopt(curl, CURLOPT_READFUNCTION, read_callback);
/* pointer to pass to our read function */
curl_easy_setopt(curl, CURLOPT_READDATA, &pooh);
size_t my_read_func(void *ptr, size_t size, size_t nmemb, void *stream)
{
FILE *fp = (FILE *)stream;
return fread(ptr, size, nmemb, fp);
}
这样发送,服务器就可以收到了。
另外感觉上面的回掉写得很巧啊。
参考:
curl库中的例子post-callback.c
http://hi.baidu.com/zhujinyu/blog/item/464522f42f634664dcc4747b.html
http://blog.sina.com.cn/s/blog_78cf66b10100rvuw.html
http://blog.chinaunix.net/link.php?url=http://curl.haxx.se%2Flibcurl%2Fc%2Fcurl_easy_setopt.html%23CURLOPTREADDATA