coco2d-x2.1.1版本已经支持了http的请求,重要的类有CCHttpRequest,CCHttpResponse,下面就写一个小例子来测试下。
向服务器发送请求,有两种形式,一种是get,一种是post,先看看get这种形式:
这种是get方法:
cocos2d::extension::CCHttpRequest* request = new cocos2d::extension::CCHttpRequest();//创建对象
request->setUrl("http://www.baidu.com");//设置请求地址
request->setRequestType(CCHttpRequest::kHttpGet);
/*请求的类型
kHttpGet,get请求
kHttpPost,post请求
kHttpUnkown 呵呵
*/
request->setResponseCallback(this, callfuncND_selector(HelloWorld::onGetFinished));//请求完的回调函数
request->setRequestData("HelloWorld",strlen("HelloWorld"));//请求的数据
request->setTag("get qing qiu baidu ");//tag
CCHttpClient::getInstance()->send(request);//发送请求
request->release();//释放内存,前面使用了new
这个种是post方法:
CCHttpRequest* request = new CCHttpRequest();
request->setUrl("http://www.httpbin.org/post");
request->setRequestType(CCHttpRequest::kHttpPost);
request->setResponseCallback(this, callfuncND_selector(HelloWorld::onGetFinished));
// write the post data
const char* postData = "visitor=cocos2d&TestSuite=Extensions Test/NetworkTest";
request->setRequestData(postData, strlen(postData));
request->setTag("POST test1");
CCHttpClient::getInstance()->send(request);
request->release();
然后看看HelloWorld::onGetFinished函数的实现
CCHttpResponse *response = (CCHttpResponse*)data;
if (!response)
{
return;
}
int s=response->getHttpRequest()->getRequestType();
int statusCode = response->getResponseCode();
char statusString[64] = {};
sprintf(statusString, "HTTP Status Code: %d, tag = %s", statusCode, response->getHttpRequest()->getTag());
if (!response->isSucceed())
{
CCLog("response failed");
CCLog("error buffer: %s", response->getErrorBuffer());
return;
}
std::vector<char> *buffer = response->getResponseData();
printf("Http Test, dump data: ");
for (unsigned int i = 0; i < buffer->size(); i++)
{
CCLog("%c", (*buffer)[i]);//这里打印从服务器返回的数据
}