直接上代码
bool HelloWorld::init()
{
//////////////////////////////
// 1. super init first
if ( !Layer::init() )
{
return false;
} HttpRequest* request = new HttpRequest();
request->setUrl("http://neoimaging.beareyes.com.cn/png2/ni_png_2_1518.png");
request->setRequestType(HttpRequest::Type::GET);
request->setResponseCallback(this, httpresponse_selector(HelloWorld::onHttpRequestCompleted));
request->setTag("GET test1");
HttpClient::getInstance()->send(request);
request->release(); return true;
} void HelloWorld::onHttpRequestCompleted(HttpClient *sender, HttpResponse *response)
{
if (!response)
{
return;
} // You can get original request type from: response->request->reqType
if ( != strlen(response->getHttpRequest()->getTag()))
{
log("%s completed", response->getHttpRequest()->getTag());
}
int statusCode = response->getResponseCode();
if (!response->isSucceed())
{
log("response failed");
log("error buffer: %s", response->getErrorBuffer());
return;
} //get data
std::vector<char> *buffer = response->getResponseData(); //create image
CCImage* img = new CCImage;
img->initWithImageData((unsigned char*)buffer->data(),buffer->size()); //create texture
cocos2d::CCTexture2D* texture = new CCTexture2D();
bool isImg = texture->initWithImage(img);
img->release(); //create sprite
CCSprite* sprite = CCSprite::createWithTexture(texture);
texture->release();
sprite->setPosition(ccp(,));
addChild(sprite,); //write file
std::string path = CCFileUtils::sharedFileUtils()->getWritablePath();
path+="download_image.png"; FILE *fp = fopen(path.c_str(), "wb+");
fwrite(buffer->data(), ,buffer->size(), fp);
fclose(fp);
}