联网游戏开发中,经常遇到http编程,接下来就分三次对cocos2dx的网络编程进阶。
本博文中先介绍建立基本的http通信并得到返回信息。
如果要使用cocos2dx的CCHttpClient来进行网络访问,则需要引入cocos2dx的相关库,详细步骤如下:
右键单击项目->属性->c/c++->常规,在右边的附件包含目录中添加cocos2dx的extensions目录对应的路径。
然后,右键单击项目->属性->链接器->输入,在右边的附件依赖项中添加libcurl_imp.lib和libExtensions.lib两个库,用分号隔开。
如果不引入extensions文件夹,会出现找不到CCHttpClient的错误;
如果不引入libcurl_imp.lib和libExtensions.lib两个库,编译项目时也会出现报错。
另外注意引入头文件:
#include "cocos-ext.h"
CCMenuItemImage *pDownloadItem = CCMenuItemImage::create( "bt_blue_light.png", "bt_blue_light.png", this, menu_selector(HelloWorld::menuDownloadCallback) ); CC_BREAK_IF(!pDownloadItem); CCSize pWinSize = CCDirector::sharedDirector()->getWinSize(); CCMenu* pDownloadMenu = CCMenu::create(pDownloadItem, NULL); pDownloadMenu->setPosition(ccp(50 ,50)); CC_BREAK_IF(! pDownloadMenu); this->addChild(pDownloadMenu, 1);添加按钮的回调函数:
void HelloWorld::menuDownloadCallback(CCObject* pSender) { cocos2d::extension::CCHttpRequest* request = new cocos2d::extension::CCHttpRequest(); request->setUrl("http://www.oschina.net/action/api/news_list"); request->setRequestType(cocos2d::extension::CCHttpRequest::kHttpPost); std::vector<std::string> headers; headers.push_back("Content-Type: application/json; charset=utf-8"); request->setHeaders(headers); const char* postData = "catalog=2&pageIndex=1&pageSize=5"; request->setRequestData(postData ,strlen(postData)); request->setResponseCallback(this, callfuncND_selector(HelloWorld::onHttpRequestCompleted)); request->setTag("Post_My_Data"); cocos2d::extension::CCHttpClient::getInstance()->send(request); request->release(); }
void HelloWorld::onHttpRequestCompleted(cocos2d::CCNode *sender ,void *data) { AllocConsole(); freopen("CONIN$", "r", stdin); freopen("CONOUT$", "w", stdout); freopen("CONOUT$", "w", stderr); cocos2d::extension::CCHttpResponse *response = (cocos2d::extension::CCHttpResponse*)data; if (!response) { return; } if (0 != strlen(response->getHttpRequest()->getTag())) { CCLog("%s completed", response->getHttpRequest()->getTag()); } int statusCode = response->getResponseCode(); char statusString[64] = {}; sprintf(statusString ,"Http status code:%d ,tag = %s" ,statusCode ,response->getHttpRequest()->getTag()); CCLog("response code:%d" ,statusCode); if (!response->isSucceed()) { CCLog("response failed"); CCLog("error buffer:%s" ,response->getErrorBuffer()); } std::vector<char> *buffer = response->getResponseData(); printf("Http response,dump data:"); std::string result = ""; for (unsigned int i = 0; i < buffer->size(); i ++) { printf("%c" ,(*buffer)[i]); } }
debug时就能看到reponse中服务器返回的数据了。
打印到窗体中:
如果还不知道如何打印到窗口,请参考:cocos2dx输出Log的几种方法
至此,我们第一步已经完成。