返回> 网站首页
libcurl使用 - http请求
yoours2017-04-26 09:44:54
简介一边听听音乐,一边写写文章。
#include <curl/curl.h>
size_t ResponseData(void* buffer,size_t size, size_t nmemb, void *stream)
{
memcpy(urlres.txt+urlres.iHeader, buffer, size*nmemb);
urlres.iHeader += size*nmemb;
return size*nmemb;
}
urlres.iHeader = 0;
memset(urlres.txt, 0, 1024);
CURL *curl = curl_easy_init();
if (!curl)
{
//fprintf(stderr,"curl init failed\n");
return 0;
}
/*
// GET方式
char* str = new char[1024];
sprintf(str, "%s?%s", url, strParamUrl);
curl_easy_setopt(curl,CURLOPT_URL, str); //url地址
//curl_easy_setopt(curl,CURLOPT_POSTFIELDS, strParamUrl); //post参数
curl_easy_setopt(curl,CURLOPT_WRITEFUNCTION, ResponseData); //对返回的数据进行操作的函数地址
//curl_easy_setopt(curl,CURLOPT_WRITEDATA,fptr); //这是write_data的第四个参数值
curl_easy_setopt(curl,CURLOPT_POST,0); //设置问非0表示本次操作为post
//curl_easy_setopt(curl,CURLOPT_VERBOSE,1); //打印调试信息
curl_easy_setopt(curl,CURLOPT_HEADER,0); //将响应头信息和相应体一起传给write_data
curl_easy_setopt(curl,CURLOPT_FOLLOWLOCATION,1); //设置为非0,响应头信息location
//curl_easy_setopt(curl,CURLOPT_COOKIEFILE,"/Users/zhu/CProjects/curlposttest.cookie");
delete[] str;
*/
// POST
curl_easy_setopt(curl,CURLOPT_URL, url); //url地址
curl_easy_setopt(curl,CURLOPT_POSTFIELDS, strParamUrl); //post参数
curl_easy_setopt(curl,CURLOPT_WRITEFUNCTION, ResponseData); //对返回的数据进行操作的函数地址
//curl_easy_setopt(curl,CURLOPT_WRITEDATA,fptr); //这是write_data的第四个参数值
curl_easy_setopt(curl,CURLOPT_POST,1); //设置问非0表示本次操作为post
//curl_easy_setopt(curl,CURLOPT_VERBOSE,1); //打印调试信息
curl_easy_setopt(curl,CURLOPT_HEADER,0); //1 将响应头信息和相应体一起传给write_data
curl_easy_setopt(curl,CURLOPT_FOLLOWLOCATION,1); //设置为非0,响应头信息location
//curl_easy_setopt(curl,CURLOPT_COOKIEFILE,"curlposttest.cookie");
CURLcode res = curl_easy_perform(curl);
curl_easy_cleanup(curl);
if (res != CURLE_OK)
{
//switch(res)
//{
// case CURLE_UNSUPPORTED_PROTOCOL:
// fprintf(stderr,"不支持的协议,由URL的头部指定\n");
// case CURLE_COULDNT_CONNECT:
// fprintf(stderr,"不能连接到remote主机或者代理\n");
// case CURLE_HTTP_RETURNED_ERROR:
// fprintf(stderr,"http返回错误\n");
// case CURLE_READ_ERROR:
// fprintf(stderr,"读本地文件错误\n");
// default:
// fprintf(stderr,"返回值:%d\n",res);
//}
return 0;
}
string jstr = UTF8_To_string(urlres.txt);
文章评论
2098人参与,0条评论