Cocos2d-x下HTTP网络通讯

引入头文件:

1 #include "cocos-ext.h"

添加下载按钮:

 1     CCMenuItemImage *pCloseItem = CCMenuItemImage::create(

 2                                         "exit.png",

 3                                         "exit.png",

 4                                         this,

 5                                         menu_selector(HelloWorld::menuCloseCallback));

 6     

 7     pCloseItem->setPosition(ccp(origin.x + visibleSize.width - pCloseItem->getContentSize().width/2 ,

 8                                 origin.y + pCloseItem->getContentSize().height/2));

 9 

10     // create menu, it's an autorelease object

11     CCMenu* pMenu = CCMenu::create(pCloseItem, NULL);

12     pMenu->setPosition(CCPointZero);

13     this->addChild(pMenu, 1);

添加回调函数:

 1 void HelloWorld::menuCloseCallback(CCObject* pSender)

 2 {

 3     std::vector<std::string> headers;

 4     headers.push_back("Content-Type: application/json; charset=utf-8");

 5     // post data

 6     const char* postData = "id=1&name=oka";

 7     unsigned int postDataLen = strlen(postData);

 8 

 9     CCHttpRequest* request = new CCHttpRequest();

10     request->setUrl("http://127.0.0.1/test.php");

11     request->setRequestType(CCHttpRequest::kHttpPost);

12     request->setResponseCallback(this, httpresponse_selector(HelloWorld::onHttpRequestCompleted));

13     request->setRequestData(postData, postDataLen);

14     request->setTag("GET test");

15     request->setHeaders(headers);

16     CCHttpClient::getInstance()->setTimeoutForConnect(3000);

17     CCHttpClient::getInstance()->send(request);

18     request->release();

19 

20 }

按钮的回调函数里向服务器发起http请求了,request->setResponseCallback(this, httpresponse_selector(HelloWorld::onHttpRequestCompleted))一行代码,向请求结束时添加了onHttpRequestCompleted回调函数

处理网络请求的回调函数:

 1 void HelloWorld::onHttpRequestCompleted(cocos2d::CCNode *sender ,void *data)

 2 {

 3     CCHttpResponse* response = (CCHttpResponse*)data;

 4     if(!response)

 5     {

 6         return;

 7     }

 8 

 9     if(0 != strlen(response->getHttpRequest()->getTag()))

10     {

11         CCLog("%s completed", response->getHttpRequest()->getTag());

12     }

13 

14     int statusCode = response->getResponseCode();

15     CCLog("Status Code: %d", statusCode);

16     if(!response->isSucceed())

17     {

18         CCLog("response failed, error buffer: %s", response->getErrorBuffer());

19         return;

20     }

21 

22     std::vector<char> *buffer = response->getResponseData();

23     std::string temp(buffer->begin(), buffer->end());

24     CCString* responseData = CCString::create(temp);

25     CCLog("%s", responseData->getCString());

26 }

执行后Log输出框中就可以看到请求结果了。

记得把request->setUrl("http://127.0.0.1/test.php");替换成测试的URL地址。

你可能感兴趣的:(cocos2d-x)