cocos2d-x HttpClient
版本:cocos2d-x2.2
联网游戏开发经常遇到http编程,写一个示例,加深记忆。
想要在cocos2d-x中使用HttpClient需要引用cocos2d-x 的相关库。
右键单击项目->属性->c/c++->常规,在右边的附件包含目录中添加cocos2dx的extensions目录对应的路径。
然后,右键单击项目->属性->链接器->输入,在右边的附件依赖项中添加libcurl_imp.lib和libExtensions.lib两个库
代码部分.h
#pragma once #include "cocos2d.h" #include "cocos-ext.h" #include "spine\Json.h" USING_NS_CC; USING_NS_CC_EXT; class HttpGet : public CCLayer { public: HttpGet(void); ~HttpGet(void); void getClicked(); static CCScene*scene(); virtual bool init(); void onGetFinished(CCNode*node,void *data); CREATE_FUNC(HttpGet); };
.cpp
#include "HttpGet.h" HttpGet::HttpGet(void) { } HttpGet::~HttpGet(void) { } CCScene*HttpGet::scene(){ CCScene*scene=NULL; do{ scene=CCScene::create(); CC_BREAK_IF(!scene); HttpGet*pLayer=HttpGet::create(); CC_BREAK_IF(!pLayer); scene->addChild(pLayer); }while(0); return scene; }; bool HttpGet::init(){ bool bRet=false; do{ glClearColor(0.0f, 0.0f, 0.0f, 1.0f); CCLayerColor*color=CCLayerColor::create(ccc4(100,100,100,20)); this->addChild(color); this->getClicked(); bRet=true; }while(0); return bRet; }; void HttpGet::getClicked(){ CCHttpRequest*request=new CCHttpRequest();//创建对象 char getData[] = "email=nubb1234@126.com&pwd=623456&nicheng=welcome2"; char url[100] ="http://i.nubb.com/mobile/adduser.htm?"; strcat(url,getData); request->setUrl(url);//添加请求地址 request->setRequestType(CCHttpRequest::kHttpGet);//设置请求类型 request->setResponseCallback(this,callfuncND_selector(HttpGet::onGetFinished));//请求完的调用函数 //request->setRequestData(getData,strlen(getData)); CCHttpClient::getInstance()->send(request);//发送请求 request->release(); }; void HttpGet::onGetFinished(CCNode*node,void *data){ AllocConsole(); freopen("CONIN$", "r", stdin); freopen("CONOUT$", "w", stdout); freopen("CONOUT$", "w", stderr); CCHttpResponse*res=(CCHttpResponse*)data; if(!res){ return; } int statusCode = res->getResponseCode(); CCLog("response code: %d", statusCode); char statusString[64] = {}; sprintf(statusString, "HTTP Status Code: %d, tag = %s", statusCode, res->getHttpRequest()->getTag()); CCLog(statusString); if (!res->isSucceed()) { CCLog("response failed"); CCLog("error buffer: %s", res->getErrorBuffer()); return; } std::vector<char> *buffer = res->getResponseData(); printf("Http Test, dump data: "); std::string rest; for (unsigned int i = 0; i < buffer->size(); i++) { rest+=(*buffer)[i]; printf("%c", (*buffer)[i]);//这里打印从服务器返回的数据 } rest+='\0'; Json*root=Json_create(rest.c_str()); Json*_result=Json_getItem(root,"Result"); if(_result->type==Json_String){ const char*result=_result->valuestring; CCLOG("recult : %s",result); } Json*_resulrStr=Json_getItem(root,"ResultStr"); if(_resulrStr->type==Json_String){ const char*resultStr=_resulrStr->valuestring; CCLOG("resultStr : %s",resultStr); } printf("\n"); Json_dispose(root); };
2.1.3版本到这里已经能运行了,但是2.2版本还要加一个库
pthreadVCE2.lib