Cocos2dx HTTP Network Programming

Source: Internet
Author: User
Tags response code


In online game development, HTTP programming is often encountered, and the next threeAdvanced Network Programming for cocos2dx.

This blog introducesEstablish basic HTTP Communication and get the returned information.

1. Create a cocos2dx project. 2. The project references the external library.

If you want to use the cchttpclient of cocos2dx for network access, you need to introduce the database of cocos2dx. The detailed steps are as follows:

Right-click Project-> properties-> C/C ++-> General, and add the corresponding path to the extensions directory of cocos2dx to the attachment directory on the right.

Then, Right-click Project-> properties-> linker-> input, and add libcurl_imp.lib and libextensions. Lib libraries to the attachment dependency on the right, separated by semicolons.

If you do not introduceIn the extensions folder, The cchttpclient cannot be found;

If you do not introduceLibcurl_imp.lib and libextensions. Lib libraries also report errors during project compilation.

Also note the introduction of header files:

#include "cocos-ext.h"  


3. Add the Download button and callback function. Add Download button:
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);

The Add button callback function:

void HelloWorld::menuDownloadCallback(CCObject* pSender){    cocos2d::extension::CCHttpRequest* request = new cocos2d::extension::CCHttpRequest();    request->setUrl("");    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();}
The callback function of the button initiates an HTTP request to the server. Request-> setresponsecallback (this, callfuncnd_selector (helloworld: onhttprequestcompleted) has a line of code, added the onhttprequestcompleted callback function at the end of the request. 4. add a callback function for the HTTP request end and read Network Data
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]);     }}

The data returned by the server in the reponse is displayed in debug.

Print to the form:



Overview there are generally six steps to use cchttpclient:
  1. Create a cchttprequest instance.
  2. Set the URL and request type.
  3. Use cchttpclient to send a request (connection URL) to the URL ).
  4. Read the response.
  5. Release the connection.
  6. Response Processing.
How to obtain a cchttprequest instance

Create a cchttprequest instance using a no-argument constructor. The cchttprequest construction method without parameters can obtain a default cchttprequest instance, which can meet most of the requirements.

cocos2d::extension::CCHttpRequest* request = new cocos2d::extension::CCHttpRequest();



Set GET request

// Set it to get request: khttpgetrequest-> setrequesttype (cocos2d: Extension: cchttprequest: khttpget); // set the callback function request for processing response-> setresponsecallback (this, callfuncnd_selector (httpclienttest: onhttprequestcompleted); Request-> settag ("Get test ");

Set POST request

// Set it to POST request: khttppostrequest-> setrequesttype (cocos2d: Extension: cchttprequest: khttppost); // set the callback function request for processing response-> setresponsecallback (this, callfuncnd_selector (httpclienttest: onhttprequestcompleted); Request-> settag ("post test ");

Send request


Process returned data (Response callback function)

Void httpclienttest: onhttprequestcompleted (cocos2d: ccnode * sender, void * Data) {cchttpresponse * response = (cchttpresponse *) data; If (! Response) {return;} // you can use: Response-> request-> reqtype to obtain the request type if (0! = Strlen (response-> gethttprequest ()-> gettag () {cclog ("% s completed", response-> gethttprequest ()-> gettag ());} // get status code int statuscode = response-> getresponsecode (); char statusstring [64] ={}; sprintf (statusstring, "HTTP status code: % d, tag = % s ", statuscode, response-> gethttprequest ()-> gettag (); m_labelstatuscode-> setstring (statusstring); cclog (" response code: % d ", statuscode); If (! Response-> issucceed () {// error message returned when access fails cclog ("response failed"); cclog ("Error Buffer: % s ", response-> geterrorbuffer (); return;} // obtain the returned data. STD: vector <char> * buffer = response-> getresponsedata (); printf ("HTTP test, dump data:"); For (unsigned int I = 0; I <buffer-> size (); I ++) {printf ("% C", (* buffer) [I]);} printf ("\ n ");}

Release connection


Do not forget to add network access permissions on the Android platform.


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.