cocos2dx 網絡編程(CCHttpRequest和CURL兩個方式)

轉自:http://blog.csdn.net/sg619262284/article/details/20144087html

在使用以前須要設置一些參數:參考:http://blog.csdn.net/wangbin_jxust/article/details/9632771json

在完成上面的操做後,還須要在連接器的輸入裏面添加一個參數pthreadVCE2.lib;cookie

使用CCHttpRequest方法實現:(異步鏈接)網絡

void HallView::Qudian()
{
   //網絡異步鏈接方法 cocos2d::extension::CCHttpRequest* postRequest=new cocos2d::extension::CCHttpRequest(); postRequest->setRequestType(cocos2d::extension::CCHttpRequest::kHttpPost);//設置發送類型 postRequest->setUrl("");//設置網址 postRequest->setResponseCallback(this,callfuncND_selector(HallView::onHttpRequestCompleted));//回調函數,處理接收到的信息 string caozuo=""; CCString *data=CCString::stringWithString(caozuo); postRequest->setRequestData(data->getCString(),data->length());//這裏的代碼會接在網絡地址後面,一塊兒發送。 cocos2d::extension::CCHttpClient* httpClient=cocos2d::extension::CCHttpClient::getInstance(); httpClient->setTimeoutForConnect(10);<span style="font-family: Arial, Helvetica, sans-serif;">//設置鏈接超時時間</span> httpClient->setTimeoutForRead(10);//設置發送超時時間 httpClient->send(postRequest);//設置接收數據類型 postRequest->release();//釋放 }

添加一個回調方法。curl

void HallView::onHttpRequestCompleted(cocos2d::CCNode *sender ,void *data)
{
cocos2d::extension::CCHttpResponse
* response=(cocos2d::extension::CCHttpResponse*)data; if(!response) {CCLOG("Log:response =null,plase check it."); return;} //請求失敗 if(!response->isSucceed()) { this->removeChildByTag(Animate_loading,true); CCDictionary* pDict = CCDictionary::createWithContentsOfFile("chines.xml"); platform::showMsg(((CCString*)pDict->objectForKey("networking"))->getCString()); 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); Json::Reader reader;//json解析 Json::Value value;//表示一個json格式的對象 if(reader.parse(responseData->getCString(),value))//解析出json放到json中區 { //這裏就能夠對返回來的信息作處理 } }

使用異步鏈接,程序和聯網的方法將互相不干擾,聯網方法將爲一個獨立的線程。異步

使用CURL方法實現:(同步鏈接)函數

第一個方法post

須要加入 頭文件#include "curl/curl.h"網站

void HallView::denglu(){    //登錄遊戲
    CURL *curl;  
    CURLcode res;  
    string cc; 
    curl=curl_easy_init();  
    if(curl)  
    { 
        curl_easy_setopt(curl, CURLOPT_URL, ""); //設置請求的地址  
        curl_easy_setopt(curl, CURLOPT_POST, true); //設置數據類型
        string caozuo="";
        curl_easy_setopt(curl, CURLOPT_POSTFIELDS,caozuo.c_str()); //將操做代碼,和鏈接的網站組合,一塊兒發送! 
        curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
        curl_easy_setopt(curl,CURLOPT_WRITEFUNCTION,HallView::writehtml); //數據處理回調函數  
        curl_easy_setopt(curl, CURLOPT_WRITEDATA, &cc);//緩衝的內存  
        curl_easy_setopt(curl,CURLOPT_TIMEOUT_MS,5000);    //設置鏈接超時時間    
        res=curl_easy_perform(curl);  
        if(res!=CURLE_OK)  
        {  
            CCDictionary* pDict = CCDictionary::createWithContentsOfFile("chines.xml");
            string mes=((CCString*)pDict->objectForKey("networking"))->getCString();
            platform::showMsg(mes);
        }  
        curl_easy_cleanup(curl);  
    }  
    else  
    {  
        CCLog("curl is null");  
    }  
}

在定義回調函數:這個方法爲靜態方法,若是裏面要引用其餘變量,須要爲靜態變量。ui

size_t HallView::writehtml(uint8_t* ptr,size_t size,size_t number,void *stream)    
{     
    CCString* a=CCString::createWithFormat("%s",ptr);  
    std::string str1=a->getCString();
    Json::Reader reader;//json解析  
    Json::Value value;//表示一個json格式的對象  
    if(reader.parse(str1,value))//解析出json放到json中區  
    {  
        string out=value["gameId"].asString();    
        gameda->gameId=out;
        out=value["newIMSI"].asString();
        gameda->newIMSI=out;
    }  
    return size*number;//這裏必定要返回實際返回的字節數    
}

在.h中定義:

static size_t writehtml(uint8_t* ptr,size_t size,size_t number,void *stream); 

使用同步鏈接,聯網方法的啓動就直接阻塞遊戲主進程的運行,直到獲取到返回值爲止。

curl_easy_setopt::屬性
curlopt_url//URL地址值
curlopt_writefunction//將獲得的數據傳遞相應的函數
curlopt_writeddata//將函數傳遞給相應的第四個參數裏
curlopt_header//若是設置爲1,能夠返回http頭的值;若是設置爲非0值,則能夠把一個頭包含在輸出中
CURLOPT_TIMEOUT_MS //設置cURL容許執行的最長毫秒數。
curlopt_low_speed_limit//設置一個長整型。控制傳送多少字節
curlopt_cookie//傳遞一個包含httpcookie的頭鏈接
curlopt_flie//傳送到輸出文件
curlopt_infile//傳送過來的輸出文件
curlopt_writeheader//輸出頭部分
curlopt_proxyuserpwd//傳遞一個形如[username]:[password]格式的字符串去鏈接http代理
curlopt_postfields//傳遞一個做爲httppost操做的全部數據的字符串
curlopt_referer //在http請求中包含一個referer頭的字符串
curlopt_useragent//在http請求中包含一個user-agent 頭的字符串
curlpot_ftpport 傳遞一個包含被ftppost指令使用的IP地址
使用格式curl_easy_setopt( curl, CURLOPT_FOLLOWLOCATION, 1L); //第一個參數實例化的curl,第二個數屬性,第三個爲屬性值

 

若是,獲取的返回值是josn格式,個人博客中有方法很是方便提取指定的值。

相關文章
相關標籤/搜索