cocos2d-x 联网函数(未做线程处理,后面补上)

采用的是http,post联网方式,url为网络地址,data为发送数据。最好不要设置网络超时时间,不然会连接不上。其中部分是加了JSON数据解析的

#include "stdio.h"
#include "stdlib.h"
#include "curl/curl.h"
#pragma comment(lib,"libcurl_imp.lib")
#include "pthread/pthread.h"
#pragma comment(lib,"pthreadVCE2.lib")
#include "cJSON.h"



void HelloWorld::dohttp(const char *url,const char *data)
{
CURL *curl;
    CURLcode res;
    int result = 1;
    string buffer;
curl_global_init( CURL_GLOBAL_ALL );
    curl = curl_easy_init();
if( curl )
       {

// curl_setopt($ch, CURLOPT_POSTFIELDS, $postfield); //设置POST提交的字符串
  
//curl_easy_setopt(curl, CURLOPT_TIMEOUT, 2000); // 超时时间
curl_slist *plist = curl_slist_append(NULL, "Content-Type: application/json; charset=UTF-8");
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, plist);
        curl_easy_setopt( curl, CURLOPT_URL, url );
curl_easy_setopt(curl, CURLOPT_POST, 1);//启用POST提交
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, data);
        curl_easy_setopt( curl, CURLOPT_FOLLOWLOCATION, 1L );
        curl_easy_setopt( curl, CURLOPT_WRITEFUNCTION, HelloWorld::writer );
        curl_easy_setopt( curl, CURLOPT_WRITEDATA, &buffer );
curl_easy_setopt(curl, CURLOPT_VERBOSE, 1);            // Used to debug
//curl_easy_setopt(curl, CURLOPT_STDERR, pFILE_error_info); // save error info in the file or stderr
       // curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, error_buff); // error_buff used to save error info
res = curl_easy_perform( curl );
curl_easy_cleanup( curl );

CCLog("json==%s",buffer.c_str());
cJSON *result= cJSON_Parse( buffer.c_str() );
cJSON *actionifo= cJSON_GetObjectItem(result,"ACTION_INFO");

}


测试数据:
dohttp(url.c_str(),data.c_str());

转载请注明出处:http://buerkai.iteye.com

你可能感兴趣的:(cocos2d-x)