void CClass::PostUpdateToUrl(CCObject* apTarget, const char* apUrl, const char* apData, unsigned long aulLength)
{
cocos2d::extension::CCHttpRequest* request = new cocos2d::extension::CCHttpRequest();
request->setUrl(apUrl);
request->setRequestType(cocos2d::extension::CCHttpRequest::kHttpPost);
std::vector<std::string> headers;
headers.push_back("Content-Type: application/json; charset=utf-8"); //根据情况修改
request->setHeaders(headers);
request->setRequestData(apData ,aulLength);
request->setResponseCallback(apTarget, httpresponse_selector(CCommHttp::onHttpRequestUpdate));
request->setTag("Post_My_Data"); //根据情况修改
cocos2d::extension::CCHttpClient::getInstance()->send(request);
request->release();
return ;
}
void CCommHttp::onHttpRequestUpdate(cocos2d::CCNode *sender ,void *data) { AllocConsole(); freopen("CONIN$", "r", stdin); freopen("CONOUT$", "w", stdout); freopen("CONOUT$", "w", stderr); cocos2d::extension::CCHttpResponse *response = (cocos2d::extension::CCHttpResponse*)data; if (!response) { return; } if (0 != strlen(response->getHttpRequest()->getTag())) { CCLog("%s completed", response->getHttpRequest()->getTag()); } int statusCode = response->getResponseCode(); // char statusString[64] = {}; // sprintf(statusString ,"Http status code:%d ,tag = %s" ,statusCode ,response->getHttpRequest()->getTag()); CCLog("response code:%d" ,statusCode); if (!response->isSucceed()) { CCLog("response failed"); CCLog("error buffer:%s" ,response->getErrorBuffer()); } std::vector<char> *buffer = response->getResponseData(); printf("Http response,dump data:"); for (unsigned int i=0; i<buffer->size(); i++) { printf("%c" ,(*buffer)[i]); }
std::string result(buffer->begin(),buffer->end()); ;CCMessageBox(result.data(), "1");
用法}
char* url = "http://www.oschina.net/action/api/news_list"; char* data = "catalog=2&pageIndex=1&pageSize=5"; PostUpdateToUrl(this, url,data ,strlen(data));