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

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

#include"stdio.h"

#include"stdlib.h"

#include"curl/curl.h"

#pragmacomment(lib,"libcurl_imp.lib")

#include"pthread/pthread.h"

#pragmacomment(lib,"pthreadVCE2.lib")

#include"cJSON.h"

voidHelloWorld::dohttp(constchar*url,constchar*data)

{

CURL*curl;

CURLcoderes;

intresult=1;

stringbuffer;

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);//Usedtodebug

//curl_easy_setopt(curl,CURLOPT_STDERR,pFILE_error_info);//saveerrorinfointhefileorstderr

//curl_easy_setopt(curl,CURLOPT_ERRORBUFFER,error_buff);//error_buffusedtosaveerrorinfo

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());

相关推荐