新建一个C++类 ,命名为NetTime,继承自CCNode并重写init()方法。然后引入CCHttpClient和rapidjson需要的头文件。我们的需求是可以返回NetTime的年,月,日,小时,分和秒,分别定义它们的PRivate字段和public方法:
#ifndef __NETTIME_H__#define __NETTIME_H__#include "cocos2d.h"#include "cocos-ext.h"#include "CocoStudio/Json/rapidjson/rapidjson.h"using namespace cocos2d;using namespace extension;using namespace rapidjson;class NetTime:public CCNode{ public: CREATE_FUNC(NetTime); int getYear(){ return _year; }; int getMonth(){ return _month; }; int getDay(){ return _day; }; int getHour(){ return _hour; }; int getMinute(){ return _minute; }; int getSecond(){ return _second; }; void getNetTime(); void requestNetTime(); private: virtual bool init(); int _year, _month, _day, _hour, _minute, _second; void onHttpComplete(CCHttpClient * sender, CCHttpResponse * response); void readJson(std::string jsonStr);};#endif我们还需要一个requestNetTime方法来发起http请求,并在回调方法里面实现数据的获取和解析,直接把前面的代码拷贝过来即可:
#include "NetTime.h"bool NetTime::init(){ bool bRet = false; do { CC_BREAK_IF(!CCNode::init()); bRet = true; } while (0); return bRet;}void NetTime::requestNetTime(){ CCHttpRequest * request = new CCHttpRequest(); request->setUrl("http://115.159.3.250:1227/WebTime.svc/"); request->setRequestType(CCHttpRequest::kHttpGet); request->setTag("WebTime"); request->setResponseCallback(this, httpresponse_selector(NetTime::onHttpComplete)); CCHttpClient::getInstance()->send(request);}void NetTime::onHttpComplete(CCHttpClient * sender, CCHttpResponse * response){ CCHttpClient::getInstance()->release(); 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: %d, tag = %s", statusCode, response->getHttpRequest()->getTag()); CCLog("%s", statusString); if (!response->isSucceed()) { CCLog("response failed"); CCLog("error buffer:%s", response->getErrorBuffer()); return; } std::vector<char> * buffer = response->getResponseData(); std::string str; for (unsigned i = 0; i < buffer->size(); i++) { char a = (*buffer)[i]; str.append(1, a); } CCLog("%s", str.c_str()); readJson(str);}void NetTime::readJson(std::string jsonStr){ Document doc; doc.Parse<0>(jsonStr.c_str()); if (!doc.IsObject()) return; if (doc.HasMember("Year") && doc.HasMember("Month") && doc.HasMember("Day") && doc.HasMember("Hour") && doc.HasMember("Minute") && doc.HasMember("Second")) { _year = doc["Year"].GetInt(); _month = doc["Month"].GetInt(); _day = doc["Day"].GetInt(); _hour = doc["Hour"].GetInt(); _minute = doc["Minute"].GetInt(); _second = doc["Second"].GetInt(); }}
新闻热点
疑难解答