首页 > 代码库 > cocos2dx 3.x(加载网络自定义头像)

cocos2dx 3.x(加载网络自定义头像)

//

//  Connection.h

//  XXDemo

//

//  Created by LeeHonGee on 14-9-4.

//

//

 

#ifndef __XXDemo__Connection__

#define __XXDemo__Connection__

 

#include <iostream>

 

#include "cocos2d.h"

#include "network/HttpClient.h"

 

 

 

USING_NS_CC;

using namespace std;

using namespace cocos2d::network;

 

class Connection{

    

public:

    

    void doHttpRequest(const char* url,const char* requestData,const char* tag,const ccHttpRequestCallback& callback);

    

   void onHttpRequestImageCompleted(HttpClient *sender, HttpResponse *response);

    

private:

    

    //获取请求网络图片资源

    Texture2D* texture;

 

};

 

#endif /* defined(__XXDemo__Connection__) */

 

 

 

 

//

//  Connection.cpp

//  XXXDemo

//

//  Created by LeeHonGee on 14-9-4.

//

//

 

#include "Connection.h"

 

 

/**

 编译到Android平台之后注意添加联网权限

 **/

void Connection::doHttpRequest(const char* url,const char* requestData,const char* tag,const ccHttpRequestCallback& callback){

  

    HttpRequest* request = new HttpRequest();

    request->setUrl(url);

    request->setRequestType(HttpRequest::Type::POST);

    

    //这是回调对象和回调函数

    request->setResponseCallback(callback);

    request->setTag(tag);

    

    //请求的数据

    if(strlen(requestData)!=0){

        request->setRequestData(requestData,strlen(requestData));

    }

    HttpClient::getInstance()->send(request);

    

    //释放内存

    request->release();

 

   }

 

void Connection::onHttpRequestImageCompleted(HttpClient *sender, HttpResponse *response){

   

    if (!response)

    {

        return;

    }

    

    // You can get original request type from: response->request->reqType

    const char* tag  =  response->getHttpRequest()->getTag();

    

    if (0 != strlen(tag))

    {

        log("%s completed", response->getHttpRequest()->getTag());

    }

    

    if (!response->isSucceed())

    {

        log("error buffer: %s", response->getErrorBuffer());

        return;

    }

    

    

    std::vector<char> *buffer = response->getResponseData();

    

    //create image

    Image* image = new Image;

    image->initWithImageData((unsigned char*)buffer->data(),buffer->size());

    

    //create texture

    texture = new Texture2D();

    bool isImage = texture->initWithImage(image);

    

    if(isImage){

        log("Texture2D 初始化!");

    }

    image->release();

    

}

 

cocos2dx 3.x(加载网络自定义头像)