转自:http://blog.sina.com.cn/s/blog_923fdd9b0102vbll.html
//
// HHttp.h
// NetTest
//
// Created by Himi on 12-10-15.
//
//
#ifndef __NetTest__HHttp__
#define __NetTest__HHttp__
#include "cocos2d.h"
using namespace cocos2d;
class HHttp{
public:
//用于与服务器交互
static bool pServer();
//用于处理服务器返回的数据
static size_t write_data(uint8_t *dataPtr, size_t size, size_t nmemb, void*stream) ;
};
#endif
HHttp.cpp
//
// HHttp.cpp
// NetTest
//
// Created by Himi on 12-10-15.
//
//
#include "HHttp.h"
//导入curl头文件
//#include "curl/curl.h"
#include "../cocos2d/external/curl/include/ios/curl/curl.h"
bool HHttp::pServer(){
//------------------------
CURL *curl; // 初始化 CURL 结构
CURLcode res;
res = curl_global_init(CURL_GLOBAL_ALL);//初始化所有的可能的调用。
if (res != CURLE_OK)
{
printf( "Failed to global init default [%d]\n", res );
return false;
}
curl = curl_easy_init();
if (curl)
{
//------preference
curl_easy_setopt(curl, CURLOPT_URL, "www.baidu.com");//设置请求的UR
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION,write_data);//绑定回调函数
// curl_easy_setopt(curl, CURLOPT_PORT, 8080);//设置请求的端口
// curl_easy_setopt(curl, CURLOPT_TIMEOUT, 30);//30秒超时
// curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, 10);//连接超时
// curl_easy_setopt(curl, CURLOPT_POST,1);//启用POST提交
//
//----send data;
// curl_easy_setopt(curl, CURLOPT_WRITEDATA, &buff);//确定数据类型uint8_t buff;
// curl_easy_setopt(curl, CURLOPT_POSTFIELDS, buff);//二进制内容
// curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, length);//数据长度
res = curl_easy_perform(curl);// post
if(res != CURLE_OK){
if (CURLE_OPERATION_TIMEDOUT == res) //连接失败 超时
{
MessageBox("Please connect to WIFI or 2G/3G", "Internet not found!");
// CCLog("网络超时:错误信息:%s\n",curl_easy_strerror(res));
return false;
}
MessageBox("Please connect to WIFI or 2G/3G", "Internet not found!");
// CCLOG("raw_send_recv : 启动 CURL 失败,错误信息:%s\n",curl_easy_strerror(res));
return false;
}
// CCLOG("~Send Data Done~~");
//清理 curl 结构,释放资源等
curl_easy_cleanup(curl);
} else {
// CCLOG("raw_send_recv : 初始化 CURL 失败 \n");
return false;
}
return true;
}
int allLength;//总流长度
std::vector<<span style="color: #703daa">uint8_t*> allData;//总数据
//服务器有数据返回的时候就会调用这个函数
size_t HHttp::write_data(uint8_t *dataPtr, size_t size, size_t nmemb, void *stream) {
int len = size * nmemb;
if(len!=1440){
// CCLOG("收到服务器数据,返回的数据长度 : %i",allLength);
}else{
allLength+=len;
allData.push_back(dataPtr);
}
size_t sizes = size * nmemb;
return sizes;
}