Cocos2d-x与服务器端数据交互(一)

从服务器端下载数据,保存到本地

加入Curl类库,在引擎中自带有

CurlUtils.h

#pragma once
#include "curl.h"
class CurlUtils
{
public:
	static void begin();
	static size_t write_data(void *ptr, size_t size, size_t nmemb, void *stream);
};
 

CurlUtils.cpp

#include "myheader.h"
#include "CurlUtils.h"
#include "curl.h"
#include "cocos2d.h"
using namespace std;
using namespace cocos2d;
void CurlUtils::begin()
{
	CURL *curl;
	CURLcode res;
	curl = curl_easy_init();
	if (curl!=NULL)
	{
		curl_easy_setopt(curl, CURLOPT_URL, "http://192.168.0.104/Test/manager/addtest.action?userName=12&password=12");
		curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data); 
		res = curl_easy_perform(curl);

	}

	curl_easy_cleanup(curl);
}

size_t CurlUtils::write_data(void *ptr, size_t size, size_t nmemb, void *stream) 
{
	FILE *fp=fopen("E:\\test.txt","w");
	int written = fwrite(ptr, size, nmemb, (FILE *)fp);
	CCLog("close");
	fclose(fp);
	return written;
}

调用:CurlUtils::begin();

相关推荐