【Cocos2d-x游戏引擎开发笔记(24)】CURL实现get和post联网

时间:2023-02-08 23:01:43

原创文章,转载请注明出处:http://blog.csdn.net/zhy_cheng/article/details/9124275

CURL是cocos2d-x推荐使用的联网方法,这种联网的方法可以跨平台。

1.环境搭建

在链接器---->输入------>附加依赖项中,添加libcurl_imp.lib,如下图:

【Cocos2d-x游戏引擎开发笔记(24)】CURL实现get和post联网

2.实现get请求:

void HelloWorld::useGet()
{
CURL *curl;
CURLcode res;

curl=curl_easy_init();
if(curl)
{
curl_easy_setopt(curl,CURLOPT_URL,"http://localhost/GameServer/servlet/getallmail?account=zhycheng");
curl_easy_setopt(curl,CURLOPT_WRITEFUNCTION,writehtml);
res=curl_easy_perform(curl);
if(res!=CURLE_OK)
{
CCLog("联网超时 %i",res);
}

curl_easy_cleanup(curl);
}
else
{
CCLog("curl is null");
return ;
}
}

这里得代码不难,看看函数名就知道意思了,curl_easy_setopt(curl,CURLOPT_WRITEFUNCTION,writehtml);这个是联网后处理数据的函数,在头文件中的声明如下:
static size_t writehtml(uint8_t* ptr,size_t size,size_t nmemb,void *stream);
在源文件中的实现如下:
size_t HelloWorld::writehtml(uint8_t* ptr,size_t size,size_t number,void *stream)
{

CCLog("%s",ptr);
return size*number;//这里一定要返回实际返回的字节数
}

这里打印出从服务器返回的数据。

2.实现post请求

post请求可以比get请求发送更多的信息
void HelloWorld::usePost()
{
CURL *curl;
CURLcode res;
std::string cc;
curl=curl_easy_init();
if(curl)
{
curl_easy_setopt( curl, CURLOPT_URL, "http://localhost/GameServer/servlet/getallmail"); //请求的地址
curl_easy_setopt(curl, CURLOPT_POST, true); //启用POST提交
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, "account=zhycheng"); //发送的数据
curl_easy_setopt( curl, CURLOPT_FOLLOWLOCATION, 1L);
curl_easy_setopt(curl,CURLOPT_WRITEFUNCTION,writehtml); //处理的函数
curl_easy_setopt( curl, CURLOPT_WRITEDATA, &cc); //缓冲的内存
res=curl_easy_perform(curl);
if(res!=CURLE_OK)
{
CCLog("联网超时 %i",res);
}


curl_easy_cleanup(curl);
}
else
{
CCLog("curl is null");
return ;
}
}

这里没什么难的,我就直接上代码了。
工程代码下载:http://download.csdn.net/detail/zhy_cheng/5607113