使用CCHttprequest联网有两种方法get和post。get和post都可以从服务器获取数据,这两种联网的方法有所不同。下面简单的区分一下
1.get提交的时候数据放到URL后面,post放在HTTP协议消息体中。
2.get数据量大小有限制,2KB,post理论上没限制。
3.get的安全性比post差。
下面来看看cocos2d-x中怎么来与服务器传递数据。
首先配置环境
#include "cocos-ext.h"
USING_NS_CC_EXT;
#pragma comment(lib,"pthreadVCE2.lib");
在VS环境下,需要配置
项目上右击-->属性-->C/C++--->常规---->附加包目录
加入如下目录D:\cocos2d-2.1beta3-x-2.1.0\extensions。
然后再在项目上右击--->属性--->链接器--->附加依赖项
添加
libcurl_imp.lib
libExtensions.lib。
get请求
void HelloWorld::getClicked(CCObject *sender)
{
//编译到Android平台之后注意添加联网权限
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请求如下
void HelloWorld::postClicked(CCObject *sender)
{
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();
}
在onGetFinished函数中,对请求的之后服务器返回的数据进行处理
void HelloWorld::onGetFinished(CCNode *node,void *data)
{
CCHttpResponse *response = (CCHttpResponse*)data;
if (!response)
{
return;
}
int s=response->getHttpRequest()->getRequestType();
CCLog("request type %d",s);
if (0 != strlen(response->getHttpRequest()->getTag()))
{
CCLog("%s ------>oked", response->getHttpRequest()->getTag());
}
int statusCode = response->getResponseCode();
CCLog("response code: %d", statusCode);
char statusString[64] = {};
sprintf(statusString, "HTTP Status Code: %d, tag = %s", statusCode, response->getHttpRequest()->getTag());
CCLog(statusString);
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]);//这里打印从服务器返回的数据
}
printf("\n");
}