Cocos2d-x3.1 HttpClient encapsulation and usage
1. First, the encapsulated tool class: HttpManager
#include "cocos2d.h"#include "../cocos2d/extensions/cocos-ext.h"#include "network/HttpClient.h"USING_NS_CC;USING_NS_CC_EXT;using namespace network;class HTTPManagerDelegate{public: virtual void onHttpManagerRequestCompleted(cocos2d::network::HttpClient *sender, cocos2d::network::HttpResponse *response) = 0;};class HTTPManager:public Ref{public: HTTPManager(); ~HTTPManager(); CC_SYNTHESIZE(HTTPManagerDelegate*, _httpManagerDelegate, HttpDelegate); //Http Response Callback void onHttpRequestCompleted(cocos2d::network::HttpClient *sender, cocos2d::network::HttpResponse *response); void getFormData(std::string parameter); void sendGetRequest(std::string url,std::string requestTag); void writeFileFromRequest(cocos2d::network::HttpResponse *response,std::string filename); typedef std::function
ccHttpManagerCallback; void addHttpListener(ccHttpManagerCallback& callback);private: ccHttpManagerCallback _eventCallback;};
# Include "HTTPManager. h" # include
// # Include "../UnZip/DJZipArchive. h" # define HTTPHeader" http://www.epicc.com.cn/QrDmzBastionNB/BastionServlet "HTTPManager: HTTPManager () {} HTTPManager ::~ HTTPManager () {} void HTTPManager: sendGetRequest (std: string url, std: string requestTag) {HttpRequest * request = new HttpRequest (); // use the HttpRequest constructor without parameters to Set request-> setRequestType (cocos2d: network: HttpRequest: Type: GET) by default ); // set the connection mode. GET and POST request-> setUrl (url. c_str (); // set the connection address // set the callback to read data from onHttpRequestCompleted request-> setResponseCallback (CC_CALLBACK_2 (HTTPManager: onHttpRequestComple Ted, this); request-> setTag (requestTag. c_str (); // set the Tag network: HttpClient: getInstance ()-> send (request); // Add it to the HttpClient task queue request-> release (); // release connection} void HTTPManager: getFormData (std: string parameter) {HttpRequest * request = new HttpRequest (); request-> setUrl (HTTPHeader ); request-> setRequestType (HttpRequest: Type: POST); request-> setResponseCallback (CC_CALLBACK_2 (HTTPManager: onHttpRequestCom Pleted, this); // write the post data const char * postData = StringUtils: format ("parameter = % s", parameter. c_str ()). c_str (); log ("postData = % s", postData); request-> setRequestData (postData, strlen (postData); request-> setTag ("getFormData "); log ("url = % s", request-> getUrl (); HttpClient: getInstance ()-> send (request); request-> release ();} void HTTPManager: onHttpRequestCompleted (cocos2d: network: Http Client * sender, cocos2d: network: HttpResponse * response) {if (! Response) {return;} if (0! = Strlen (response-> getHttpRequest ()-> getTag () {log ("% s compeled", response-> getHttpRequest ()-> getTag ());} long statusCode = response-> getResponseCode (); char statusString [64] ={}; sprintf (statusString, "HTTP Status Code: % ld, tag = % s", statusCode, response-> getHttpRequest ()-> getTag (); log ("response code: % s", statusString); if (! Response-> isSucceed () {log ("response failed"); log ("error buffer: % s", response-> getErrorBuffer (); return ;} if (_ httpManagerDelegate) {_ httpManagerDelegate-> onHttpManagerRequestCompleted (sender, response);} const char * resTag = response-> getHttpRequest ()-> getTag ();} void HTTPManager :: writeFileFromRequest (cocos2d: network: HttpResponse * response, std: string filename) {std: vector
* Buffer = response-> getResponseData (); printf ("Http Test, dump data:"); std: string path = FileUtils: getInstance ()-> getWritablePath (); std: string fullPath = path + filename; FILE * fp = fopen (fullPath. c_str (), "wb"); log ("Write File locally % s", fullPath. c_str (); unsigned char bf; for (unsigned int I = 0; I <buffer-> size (); I ++) {bf = buffer-> at (I); fwrite (& bf, 1, 1, fp);} fclose (fp);} void HTTPManager: addHttpListener (ccHttpManagerCallback & callback) {_ eventCallback = callback ;}
To improve code availability, some methods and interfaces are not used here, but they will be used in case of future use. Let's take a look at the example below.
2. Use instances
The use class must inherit HttpManagerDelegate to delegate events.
#include "cocos2d.h"#include "HTTPManager.h"USING_NS_CC;class HelloWorld : public cocos2d::Layer,public HTTPManagerDelegate{public: // there's no 'id' in cpp, so we recommend returning the class instance pointer static cocos2d::Scene* createScene(); // Here's a difference. Method 'init' in cocos2d-x returns bool, instead of returning 'id' in cocos2d-iphone virtual bool init(); // a selector callback void menuCloseCallback(cocos2d::Ref* pSender); virtual void onHttpManagerRequestCompleted(cocos2d::network::HttpClient *sender, cocos2d::network::HttpResponse *response) ; void writeFileFromRequest(cocos2d::network::HttpResponse *response,std::string filename); // implement the "static create()" method manually CREATE_FUNC(HelloWorld);};
# Include "HelloWorldScene. h "# include" HTTPManager. h "USING_NS_CC; Scene * HelloWorld: createScene () {// 'Scene 'is an autorelease object auto scene = scene: create (); // 'player' is an autorelease object auto layer = HelloWorld: create (); // add layer as a child to scene-> addChild (layer ); // return the scene return scene;} // on "init" you need to initialize your instancebool HelloWorld: init (){/ /// // 1. super init first if (! Layer: init () {return false;} Size visibleSize = Director: getInstance ()-> getVisibleSize (); Vec2 origin = Director: getInstance () -> getVisibleOrigin (); // 2. add a menu item with "X" image, which is clicked to quit the program // you may modify it. // add a "close" icon to exit the progress. it's an autorelease object auto closeItem = MenuItemImage: create ("CloseNo Rmal.png "," CloseSelected.png ", CC_CALLBACK_1 (HelloWorld: menuCloseCallback, this); closeItem-> setPosition (Vec2 (origin. x + visibleSize. width-closeItem-> getContentSize (). width/2, origin. y + closeItem-> getContentSize (). height/2); // create menu, it's an autorelease object auto menu = Menu: create (closeItem, NULL); menu-> setPosition (Vec2 :: ZERO); this-> addChild (menu, 1); auto httpManager = new HT TPManager (); httpManager-> retain (); httpManager-> setHttpDelegate (this); httpManager-> sendGetRequest ("localhost: 8080/qwe. json "," update_time "); return true;} void HelloWorld: onHttpManagerRequestCompleted (cocos2d: network: HttpClient * sender, cocos2d: network: HttpResponse * response) {if (strcmp (response-> getHttpRequest ()-> getTag (), "update_time") = 0) {writeFileFromRequest (response, "qwe. json "); l Og ("Download update package"); std: string version = "version"; std: string table = "version"; if (! (Strcmp (version. c_str (), table. c_str () = 0) {log ("Download update package"); # if (CC_TARGET_PLATFORM = CC_PLATFORM_ANDROID) # endif }} if (strcmp (response-> getHttpRequest ()-> getTag (), "update_mobile") = 0) {log ("update_mobile ");}} void HelloWorld: writeFileFromRequest (cocos2d: network: HttpResponse * response, std: string filename) {std: vector
* Buffer = response-> getResponseData (); printf ("Http Test, dump data:"); std: string path = FileUtils: getInstance ()-> getWritablePath (); std: string fullPath = path + filename; FILE * fp = fopen (fullPath. c_str (), "wb"); log ("Write File locally % s", fullPath. c_str (); // auto size = buffer-> size (); // unsigned char bf [size]; // fwrite (bf, size, 1, fp ); unsigned char bf; for (unsigned int I = 0; I <buffer-> size (); I ++) {bf = buffer-> at (I ); fwrite (& bf, 1, 1, fp) ;}fclose (fp) ;}void HelloWorld: menuCloseCallback (Ref * pSender) {# if (CC_TARGET_PLATFORM = CC_PLATFORM_WP8) | (CC_TARGET_PLATFORM = CC_PLATFORM_WINRT) MessageBox ("You pressed the close button. windows Store Apps do not implement a close button. "," Alert "); return; # endif Director: getInstance ()-> end (); # if (CC_TARGET_PLATFORM = CC_PLATFORM_IOS) exit (0); # endif}
3. Usage class
You only need to inherit the HttpManagerDelegate delegate to implement function callback. Second, you need to build a server. We have studied the delegate callback of functions.
(1) set two parameters setHttpManagerDelegate (this) to facilitate the callback of the onHttpManagerRequestCompleted function of the HelloWorld class.
(2) Set setGetRequest (). The first parameter is URL, and the second parameter is Tag.
4. Process
Eclipse ADT imports the HttpServer project and runs it to run the server.
Disable the network connection.
Run cocos2d-x Engineering
Enter: localhost: 8080/file name in the address bar of the webpage
Note: You must modify the background path for saving the file.
Source code link: http://download.csdn.net/user/yuxikuo_1/uploads