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)。



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值