cocos2d-x中使用Http

一、如何使用

//发送接口
void CmdHelper::postRequest(const char* cmdTag, const char* url, const char* postData, size_t postDataLengt)
{
CCHttpRequest* request = new CCHttpRequest();
request->setTag(cmdTag);
request->setUrl(url);
request->setResponseCallback(this, httpresponse_selector(CmdHelper::onRequestRsp)); //set request type: get/post/put/delete
request->setRequestType(CCHttpRequest::kHttpPost); //set header
std::vector<std::string> headers;
headers.push_back("Content-Type: application/json; charset=utf-8");
request->setHeaders(headers); //set body data, POST only
request->setRequestData(postData, postDataLengt); //set time out
CCHttpClient::getInstance()->setTimeoutForConnect(TIMEOUT_CONNECT);
CCHttpClient::getInstance()->setTimeoutForRead(TIMEOUT_READ);
CCHttpClient::getInstance()->send(request);
// don't forget to release it, pair to new
request->release();
} #define CMD_DOWNLOAD "CMD_DOWNLOAD"
#define URL_DOWNLOAD "http://192.168.2.122:9001/star/downsolution"
std::string data = "";
//发送post请求时,调用如下接口即可
postRequest(CMD_DOWNLOAD, URL_DOWNLOAD, data.c_str(), data.length()); //接收回调
void CmdHelper::onRequestRsp(CCHttpClient* client, CCHttpResponse* response)
{
if (!response)
{
CCLOG("ERROR: %s ---> null response", __FUNCTION__);
return;
} std::string tag = response->getHttpRequest()->getTag();
int statusCode = response->getResponseCode();
CCLOG("%s ---> response code: %d, tag = %s", __FUNCTION__, statusCode, tag.c_str()); std::string dataBody;
if (!response->isSucceed())
{
CCLOG("response failed");
CCLOG("error buffer: %s", response->getErrorBuffer());
//this->setLastNetworkError(response->getErrorBuffer());
}
else
{
// dump data
std::vector<char> *buffer = response->getResponseData();
dataBody.assign(buffer->begin(), buffer->end());
//CCLOG("%s", dataBody.c_str());
} //dispatch
if (CMD_DOWNLOAD == tag)
{
this->onDownloadTaskSolutionRsp(dataBody.c_str(), dataBody.size());
}
else
{
CCLOG("%s ---> error branch, cmd tag = %d", __FUNCTION__, tag.c_str());
}
}

二、遇到的坑

1. 注意传输的编码格式
如上示例中,我们使用的utf-8编码,但是在http传输二进制数据的时候,服务器收到的数据变大了,所以要么改传输的编码格式,要么把本地要传输的二进制数据转码(比如我们用的base64)。

上一篇:[转载]将别人的项目或JAVA文件导入到自己的Eclipse中时,常常会出现JAVA文件的中文注释变成乱码的情况,解决办法


下一篇:正则表达式-python-无捕获分组与分支选择