coco2d-x 2.1.3 之 使用网络请求

1.使用get方式请求

void HttpClientHelper::testGetRequestMethod()

 {

 cocos2d::extension::CCHttpRequest* getRequest=new cocos2d::extension::CCHttpRequest();

 getRequest->setRequestType(cocos2d::extension::CCHttpRequest::kHttpGet);

 getRequest->setUrl("http://www.baidu.com");

 getRequest->setTag("GET");

 getRequest->setResponseCallback(this, callfuncND_selector(HttpClientHelper::testGetCallbackMethod));

 

 cocos2d::extension::CCHttpClient::getInstance()->send(getRequest);

 

 getRequest->release();

 

 }

 

 void HttpClientHelper::testGetCallbackMethod(cocos2d::CCNode* sender, void* data)

 {

 CCLOG("log:testGetCallbackMethod");

 

 cocos2d::extension::CCHttpResponse* response=(cocos2d::extension::CCHttpResponse*)data;

 if(!response) return;

 

 if(!response->isSucceed())

 {

 CCLOG("RESPONSE FAILED!");

 CCLOG("ERROR BUFFER:%s",response->getErrorBuffer());

 return;

 }

 

 char statusString[64]={};

 sprintf(statusString, "HTTP STATUS CODE:%d,TAG=%s",response->getResponseCode(),response->getHttpRequest()->getTag());

 CCLOG(statusString);

 

 std::vector<char>* buffer=response->getResponseData();

 char* concatenated=(char*)malloc(buffer->size()+1);

 std::string s2(buffer->begin(),buffer->end());

 strcpy(concatenated, s2.c_str());

 CCLOG(concatenated);

 CCLog("\n\n\n\n\n");

 }

2.使用post方式请求

void HttpClientHelper::PostRequestMethod(CCString* data)
{ cocos2d::extension::CCHttpRequest
* postRequest=new cocos2d::extension::CCHttpRequest(); postRequest->setRequestType(cocos2d::extension::CCHttpRequest::kHttpPost); postRequest->setUrl("http://baidu.com"); postRequest->setTag("Post"); postRequest->setResponseCallback(this,callfuncND_selector(HttpClientHelper::PostCallbackMethod)); postRequest->setRequestData(data->getCString(), data->length()); cocos2d::extension::CCHttpClient* httpClient=cocos2d::extension::CCHttpClient::getInstance(); httpClient->send(postRequest); /*cocos2d::extension::CCHttpClient::getInstance()->send(postRequest);*/ postRequest->release(); //httpClient->release(); } void HttpClientHelper::PostCallbackMethod(cocos2d::CCNode* sender) { CCLOG("log:testPostCallbackMethod"); /*cocos2d::extension::CCHttpClient::destroyInstance();*/ cocos2d::extension::CCHttpResponse* response=(cocos2d::extension::CCHttpResponse*)data; if(!response) {CCLOG("Log:response =null,plase check it."); return;} //请求失败 if(!response->isSucceed()) { CCLOG("ERROR BUFFER:%s",response->getErrorBuffer()); return; } int codeIndex=response->getResponseCode(); const char* tag=response->getHttpRequest()->getTag(); //请求成功 std::vector<char>* buffer=response->getResponseData(); std::string temp(buffer->begin(),buffer->end()); CCString* responseData=CCString::create(temp); CCLog("%s",responseData->getCString()); }

 

你可能感兴趣的:(网络)