Cocos2d-x中 发起http请求

前端之家收集整理的这篇文章主要介绍了Cocos2d-x中 发起http请求前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

bool httpTool::httpRequest(char * tag,char * url,char * requestdata,int requestType)

{

// 请求示例
//CCHttpRequest* request = new CCHttpRequest();
//request->setUrl(url /*"http://httpbin.org/delete"*/);
//request->setRequestType((CCHttpRequest::HttpRequestType)requestType/*CCHttpRequest::kHttpDelete*/);
//request->setResponseCallback(this,httpresponse_selector(CCSceneEx::onHttpRequestCompleted));
//request->setTag(tag/*"DELETE test2"*/);
//CCHttpClient::getInstance()->send(request);
//request->release();


//实际代码

if (tag == 0 || tag[0] == '\0' || url == 0 || url[0] = '\0' || requestType < 0 || requestType > (int)network::HttpRequest::Type::UNKNOWN)

{

return false;

}

//请求的大体思路是

//1.使用network::HttpRequest构造要请求的数据

//2.使用network::HttpClient使用这个作为发射器把数据发射出去

network::HttpRequest * request = new network::HttpRequest();

request->setUrl(url); //设置请求地址

request->setRequestType((network::HttpRequest::Type)requestType); //设置请求类型 ,有GET,POST,PUT,DELETE,UNKNOWN 五钟

if (requestdata != 0 && requestdata[0] != '\0') //如果有请求参数

{

request->setRequestData[requestdata,strlen(requestdata)); //设置请求参数

}

network::ccHttpRequestCallback httpRequestCallback = std::bind(&CCSceneEx::onHttpRequestCompleted,this,std::placeholder::-1,std::placeholder::_2);

request->setResponseCallback(httpRequestCallback); //设置回调函数

request->setTag(tag); //设置标签

network::HttpClient::getInstance()->send(request); //发送请求

request->release(); //释放请求

}


//httpRequest回调函数

void httpTool::onHttpRequestCompleted(network::HttpClient * sender,network::HttpResponse * response)

{

if (!response)

{

return;

}

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

if(0 != strlen(pTag))

{

}

int ret = 0;

int statusCode = response->getResponseCode();

char * buffer = 0;

int bufferSize = 0;

char * errorInfo = "";

if (response->isSucceed())

{

ret = 1;

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

bufferSize = vbuffer->size();

buffer = new char[bufferSize + 1];

for (int i = 0; i < bufferSize; ++i)

{

buffer[i] = (*vbuffer)[i];

}

buffer[bufferSize] = '\0';

}

else

{

ret = 0;

errorInfo = (char *)response->getErrorBuffer();

}

CLuaParam luaParams[6];

luaParams[0] = ret;

luaParams[1] = statusCode;

luaParams[2] = pTag;

luaParams[3] = bufer;

luaParams[4] = bufferSize;

luaParams[5] = errorInfo;


LuaCppData::sharedLuaCppData()->RunLuaFunction("NetUpdate_OnHttpRequestCompleted",luaParams,6);

if (buffer != 0)

{

delete[] buffer;

}

}

猜你在找的Cocos2d-x相关文章