cocos2d-x中使用Http

前端之家收集整理的这篇文章主要介绍了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",tag.c_str());
	}
}


二、遇到的坑

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

原文链接:/cocos2dx/343091.html

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