HTTP請求實現,把下面代碼複製到新創建的工程中就能看到效果.
HelloWorldScene.h
#include "cocos2d.h"
/*記得要引頭文件*/
#include "extensions/cocos-ext.h"
#include "network/HttpClient.h"
USING_NS_CC;
USING_NS_CC_EXT;
using namespace network;
class HelloWorld : public cocos2d::Layer
{
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);
void onMenuGetTestClicked(Ref* sender);
void onMenuPostBinaryTestClicked(Ref* sender);
//Http Response Callback
void onHttpRequestCompleted(cocos2d::network::HttpClient *sender, cocos2d::network::HttpResponse *response);
// implement the "static create()" method manually
CREATE_FUNC(HelloWorld);
};
HelloWorldScene.cpp
#include "HelloWorldScene.h"
USING_NS_CC;
Scene* HelloWorld::createScene()
{
// 'scene' is an autorelease object
auto scene = Scene::create();
// 'layer' is an autorelease object
auto layer = HelloWorld::create();
// add layer as a child to scene
scene->addChild(layer);
// return the scene
return scene;
}
// on "init" you need to initialize your instance
bool 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(
"CloseNormal.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 winSize = Director::getInstance()->getWinSize();
const int MARGIN = 40;
const int SPACE = 70;
auto label = Label::create("Http Request Test", "fonts/arial.ttf", 28);
label->setPosition(Vec2(winSize.width / 2, winSize.height - MARGIN));
addChild(label);
auto menuRequest = Menu::create();
menuRequest->setPosition(Point::ZERO);
addChild(menuRequest);
//Get
auto labelGet = Label::createWithTTF("Test Get", "fonts/arial.ttf", 44);
auto itemGet = MenuItemLabel::create(labelGet, CC_CALLBACK_1(HelloWorld::onMenuGetTestClicked, this));
itemGet->setPosition(Point(winSize.width / 2, winSize.height - MARGIN - SPACE));
menuRequest->addChild(itemGet);
auto labelPostBinary = Label::createWithTTF("Test Post Binary", "arial.ttf", 44);
auto itemPostBinary = MenuItemLabel::create(labelPostBinary, CC_CALLBACK_1(HelloWorld::onMenuPostBinaryTestClicked, this));
itemPostBinary->setPosition(Point(winSize.width / 2, winSize.height - MARGIN - 3 * SPACE));
menuRequest->addChild(itemPostBinary);
return true;
}
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
}
void HelloWorld::onMenuGetTestClicked(Ref* sender)
{
HttpRequest* request = new HttpRequest();
request->setUrl("GET請求網址");
request->setRequestType(HttpRequest::Type::GET);
request->setResponseCallback(this, httpresponse_selector(HelloWorld::onHttpRequestCompleted));
request->setTag("GET test1");
HttpClient::getInstance()->send(request);
request->release();
}
void HelloWorld::onMenuPostBinaryTestClicked(cocos2d::Ref *sender)
{
HttpRequest* request = new HttpRequest();
request->setUrl("https://www.baidu.com/");
request->setRequestType(HttpRequest::Type::POST);
request->setResponseCallback(this, httpresponse_selector(HelloWorld::onHttpRequestCompleted));
const char* postData = "參數 params = Value";
request->setRequestData(postData,strlen(postData) );
request->setTag("POST test1");
HttpClient::getInstance()->send(request);
request->release();
}
void HelloWorld::onHttpRequestCompleted(cocos2d::network::HttpClient *sender, cocos2d::network::HttpResponse *response)
{
if (!response) {
return;
}
if (0 != strlen(response->getHttpRequest()->getTag())) {
log("%s completed",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: %ld",statusCode);
if (!response->isSucceed()) {
log("response failed");
log("error buffer: %s",response->getErrorBuffer());
return;
}
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");
}