<img src="http://img.blog.csdn.net/20150130143712925?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvb3FxUXVaaTEyMzQ1Njc=/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center" alt="" />
#include "HttpRequest.h" #include "HttpClient.h" USING_NS_CC; USING_NS_CC_EXT; using namespace std; class StartScene : public cocos2d::CCLayer{ public: bool init(); void onEnter(); void onGetFinished(cocos2d::extension::CCHttpClient *target,CCObject *obj); void menuCloseCallback(CCObject* pSender); cocos2d::CCSprite *sp; private: };
void StartScene::onEnter(){ CCLayer::onEnter(); // 这是个静态方法 得到一个httpClient实例 CCHttpClient *httpClient = CCHttpClient::getInstance(); // 创建一个httpRequest对象 CCHttpRequest *httprequest = new CCHttpRequest(); // 设置请求类型 httprequest->setRequestType(CCHttpRequest::kHttpGet); // 设置请求URL httprequest->setUrl("http://113.106.90.141:2020/Upload/2015/1/28/464d4345-7675-4d49-9c5c-ee16483eae46_640_300.png"); // 设置回调 httprequest->setResponseCallback(this, httpresponse_selector(StartScene::onGetFinished)); // 设置标签 httprequest->setTag("get image"); // 设置连接超时时间 httpClient->setTimeoutForConnect(30); // 发送请求 httpClient->send(httprequest); // 释放httprequest httprequest->release(); httprequest=NULL; }
void StartScene::onGetFinished(CCHttpClient *target,CCObject *obj) { CCHttpResponse *response = (CCHttpResponse*)obj; // 判断是否响应成功 if (!response->isSucceed()) { CCLOG("Receive Error: %s\n",response->getErrorBuffer()); return; } //数据转存 unsigned char * pBuffer = NULL; unsigned long bufferSize = 0; vector<char>* buffer = response->getResponseData(); string path = CCFileUtils::sharedFileUtils()->getWritablePath()+"test.png"; pBuffer = CCFileUtils::sharedFileUtils()->getFileData(path.c_str(), "r", &bufferSize); // vector<char> 转 string string buff(buffer->begin(),buffer->end()); //保存到本地文件 CCLOG("path: %s",path.c_str()); FILE *fp = fopen(path.c_str(), "wb+"); fwrite(buff.c_str(), 1, buffer->size(), fp); }
void StartScene::menuCloseCallback(CCObject* pSender) { unsigned char* pBuffer = NULL; unsigned long bufferSize = 0; string path = CCFileUtils::sharedFileUtils()->getWritablePath()+"test.png"; pBuffer = CCFileUtils::sharedFileUtils()->getFileData(path.c_str(), "r", &bufferSize); if (!pBuffer) { return ; } CCImage* img = new CCImage; img->initWithImageData(pBuffer,bufferSize); free(pBuffer); CCTexture2D* texture = new cocos2d::CCTexture2D(); bool isImg = texture->initWithImage(img); img->release(); if (!isImg) { delete texture; return ; } //这里建议使用成员变量来保存精灵,不然有可能导致显示白色块,出现异常! sp =CCSprite::createWithTexture(texture); CCSprite* sprite = CCSprite::createWithTexture(sp->getTexture()); sprite->setPosition(ccp(240,160)); this->addChild(sprite,10); texture->release(); return; }