前面轉載了兩篇有關cURL的文章,都很詳細 。說實話,看的不是很懂。下面通過引擎中的一個例子來看看。
(1)關於這個curl這個類的檔案所在位置,libs/cocos2dx/platform/third_party/ios/curl 就可以看到curl有關的檔案了。
(2)關於引擎中內建的例子:CurlTest
其中與curl有關的代碼如下:
void CurlTest::ccTouchesEnded(CCSet *pTouches, CCEvent *pEvent){ CURL *curl; CURLcode res; char buffer[10]; curl = curl_easy_init(); if (curl) { curl_easy_setopt(curl, CURLOPT_URL, "www.google.com"); res = curl_easy_perform(curl); /* always cleanup */ curl_easy_cleanup(curl); if (res == 0) { m_pLabel->setString("0 response"); } else { sprintf(buffer,"code: %i",res); m_pLabel->setString(buffer); } } else { m_pLabel->setString("no curl"); } }
(3)下面是一個類似的代碼:
注意添加: curl_global_init(CURL_GLOBAL_DEFAULT)
-- 全域初始化函數,程式中只調用一次。參數包括:
#define CURL_GLOBAL_SSL (1<<0)#define CURL_GLOBAL_WIN32 (1<<1)#define CURL_GLOBAL_ALL (CURL_GLOBAL_SSL|CURL_GLOBAL_WIN32)#define CURL_GLOBAL_NOTHING 0#define CURL_GLOBAL_DEFAULT CURL_GLOBAL_ALL
//定義的寫資料的回呼函數。 但是在回呼函數中只是將擷取到的資料輸出而已size_t write_data(void *buffer, size_t size, size_t nmemb, void *stream){ printf("%s",(char*)buffer); return size*nmemb;//這裡一定要返回實際返回的位元組數}//修改觸屏結束的函數處理。void HelloWorld::ccTouchesEnded(CCSet *pTouches, CCEvent *pEvent){ //首先,使用CURL必須要建立一個CULR指標,它是CURL的全域控制代碼。 CURL *curl; //這裡定義一個CURL庫中API的傳回值,用於取得API調用的結果。 CURLcode res; //第一步:初始化CURL,取得初始化成功後的CURL指標。 curl = curl_easy_init(); if(curl) { //第二步,設定我們用此CURL指標來完成的動作。參數一為CURL指標,參數二為相應的動作類型枚舉,這個枚舉值在curl.h中定義,比如本例中的CURLOPT_URL,定義為CINIT(URL, OBJECTPOINT, 2),即聯結一個網站的HTTP服務。參數三為動作對應的資料參數,這裡是網站的URL地址。 curl_easy_setopt(curl, CURLOPT_URL, "http://www.baidu.com"); // curl_easy_setopt //設定寫資料的回呼函數。 res = curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data); if(res != CURLE_OK){ printf("curl_easy_setopt not return CURLE_OK\n"); } else{ printf("curl_easy_setopt exec success\n"); } //第三步,執行上面設定的動作處理。返回結果放在res中。 res = curl_easy_perform(curl); if(res != CURLE_OK){ printf("curl_easy_perform not return CURLE_OK\n"); } else{ printf("curl_easy_perform exec success\n"); } /* always cleanup */ //最後一步,清除CURL指標,結束對CURL庫的使用。 curl_easy_cleanup(curl); } }
解釋一下這段代碼:啟動程式,點擊螢幕,觸發touchEnded這個函數,在這個函數中連網到www.baidu.com,在回調方法中輸出擷取到的資料,將這些資料儲存為html檔案,雙擊這個檔案,就是百度首頁介面了。
遊戲運行終端輸出:
curl_easy_setopt exec success
<!DOCTYPE html><!--STATUS OK--><html><head><meta http-equiv="content-type" content="text/html;charset=utf-8"><title>百度一下,你就知道</title><style >html,body{height:100%}html{overflow-y:auto}#wrapper{position:relative;_position:;min-height:100%}#content{padding-bottom:100px;text-align:center}#ftCon{height:100px;position:absolute;bottom:44px;text-。。。。。。。。。。。。。。。。。
curl_easy_perform exec success
總結:說實話,對應cURL確實是不懂,現在剛剛開始,有點印象,以後用的再深入瞭解吧!