curllib库http chunk发送方法纠错

                                                curllib库http chunk发送方法纠错

以前一直以为发送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


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值