您的位置:首页 > 移动开发 > Cocos引擎

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

2015-03-04 14:10 525 查看
转载自:/article/1389498.html

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

1.环境搭建

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



2.实现get请求:

[cpp] view
plaincopy

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);这个是联网后处理数据的函数,在头文件中的声明如下:

[cpp] view
plaincopy

static size_t writehtml(uint8_t* ptr,size_t size,size_t nmemb,void *stream);

在源文件中的实现如下:

[cpp] view
plaincopy

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请求发送更多的信息

[cpp] view
plaincopy

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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: