转载出处:http://blog.csdn.net/zhy_cheng/article/details/9124275
CURL是cocos2d-x推荐使用的联网方法,这种联网的方法可以跨平台。
1.环境搭建
在链接器---->输入------>附加依赖项中,添加libcurl_imp.lib,如下图:
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);
- 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 ;
- }
- }
这里没什么难的,我就直接上代码了。