0. 环境:
winxpsp3, vs2010, cocos2dx@2.1.4
1. 新建一个Helloworld工程
2. HelloworldScene.h里面重写virtual bool ccTouchBegan( cocos2d::CCTouch *pTouch, cocos2d::CCEvent *pEvent );
3. .cpp看代码:
关注点在write_callback() 和 ccTouchBegan()的重写
4. c盘创建个空文件C:\baidu.html
5. 实现的功能就是点一下屏幕发出一次http get request, 然后在指定的文件里面填充上服务器返回的网页.
#include "HelloWorldScene.h" #include "cocos-ext.h" #include "curlcurl.h" #include <string> using namespace std; USING_NS_CC; USING_NS_CC_EXT; //////////////////////////////////// CCScene* HelloWorld::scene() { // 'scene' is an autorelease object CCScene *scene = CCScene::create(); // 'layer' is an autorelease object HelloWorld *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() { if ( !CCLayer::init() ) { return false; } pLabel = CCLabelTTF::create("Hello World", "airal", 34); CCSize size = CCDirector::sharedDirector()->getWinSize(); pLabel->setPosition( ccp(size.width / 2, size.height - 20) ); this->addChild(pLabel, 1); setTouchMode(kCCTouchesOneByOne); setTouchEnabled(true); return true; } void HelloWorld::menuCloseCallback(CCObject* pSender) { CCDirector::sharedDirector()->end(); #if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS) exit(0); #endif } size_t write_callback(void *ptr, size_t size, size_t nmemb, FILE *stream) { size_t written = fwrite(ptr, size, nmemb, (FILE *)stream); return written; } bool HelloWorld::ccTouchBegan( CCTouch *pTouch, CCEvent *pEvent ) { CCLog("go into ccTouchBegan"); CURL *curl; CURLcode res; char buffer[10]; curl = curl_easy_init(); if (curl) { FILE *outfile; outfile = fopen("C:\baidu.html", "wb"); //curl_easy_setopt(curl, CURLOPT_URL, "blog.csdn.net"); curl_easy_setopt(curl, CURLOPT_URL, "http://127.0.0.1:8080/wuziqi?name=1715"); if(outfile) { //指定写入的文件指针。 curl_easy_setopt(curl, CURLOPT_FILE, outfile); } //设置写数据的回调函数。 curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_callback); res = curl_easy_perform(curl); /* always cleanup */ curl_easy_cleanup(curl); fclose(outfile); if (res == 0) { pLabel->setString("0 response"); } else { sprintf(buffer,"code: %i",res); pLabel->setString(buffer); } } else { pLabel->setString("no curl"); } /////////////////////////////////////////////////////////// return true; } /*size_t HelloWorld::funcCallback( void* ptr,size_t size,size_t number,void *stream ) { CCString* a = CCString::createWithFormat("%s",ptr); this->pLabel->setString(a->getCString()); CCLog(a->getCString()); CCLog("go into writehtml"); return size*number;//这里一定要返回实际返回的字节数 }*/