Cocos2dx Curl 的导入使用 (libcurl.lib)
Cocos2dx curl 的导入使用
cocos2dx第三方库里面有包含curl库
=====================================
1. 新建项目CurlDemo
Additional Include Directories (C\C++ -> General) 添加:$(EngineRoot) $(EngineRoot)external\curl\include\win32\curl Additional Libray Directories(Linker -> General) $(EngineRoot)external\curl\prebuilt\win32 Additional Dependencies(Linker -> Input) libcurl_imp.lib websockets.lib //也可在头文件:#pragma comment(lib,"libcurl_imp.lib")
2.直接在HelloWorldScene.cpp里面 插入代码:
头文件部分:
#include "cocos2d.h" #include "curl\include\win32\curl\curl.h" #include <string> #pragma comment(lib,"libcurl_imp.lib")
Request访问:
bool HelloWorld::init() { ... ... /* 请求登陆 (curl) */ //加载动态链接库 /* HINSTANCE hinstance=NULL; hinstance = LoadLibrary("D:\\cocos\\cocos2d-x-3.6\\external\\curl\\prebuilt\\libcurl.dll"); */ CURL *curl; CURLcode res; std::string cc; curl=curl_easy_init(); if(curl) { curl_easy_setopt(curl, CURLOPT_URL, "http://127.0.0.1:8080/hello/"); //设置请求的地址 curl_easy_setopt(curl, CURLOPT_POST, true); //设置数据类型 std::string caozuo=""; curl_easy_setopt(curl, CURLOPT_POSTFIELDS,caozuo.c_str()); //将操作代码,和连接的网站组合,一起发送! curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L); curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, writehtml); //数据处理回调函数 curl_easy_setopt(curl, CURLOPT_WRITEDATA, &cc);//缓冲的内存 curl_easy_setopt(curl, CURLOPT_TIMEOUT_MS, 5000); //设置连接超时时间 res=curl_easy_perform(curl); if(res!=CURLE_OK) { log("-----%d", res); } curl_easy_cleanup(curl); } else { log("curl is null"); } return true; }
Response回调函数
USING_NS_CC; ... ... // curl size_t writehtml(uint8_t* ptr,size_t size,size_t number,void *stream) { CCString* a=CCString::createWithFormat("%s",ptr); std::string str1=a->getCString(); //Json::Reader reader;//json解析 //Json::Value value;//表示一个json格式的对象 //if(reader.parse(str1,value))//解析出json放到json中区 //{ // string out=value["gameId"].asString(); // gameda->gameId=out; // out=value["newIMSI"].asString(); // gameda->newIMSI=out; //} log("--writehtml---%s", str1.c_str()); return size*number;//这里一定要返回实际返回的字节数 } ... ... Scene* HelloWorld::createScene() ... ...
--- THE END !!
浙公网安备 33010602011771号