配置:win7+Cocos2d-x.3.0+VS2012
摘要:建立基本的http通信并得到返回信息。
在需要用到Http网络相关类的文件中加入头文件
#include "network/HttpClient.h"
路径:%工作目录%\cocos2d\cocos\network\proj.win32
位置:项目-右键-属性-通用属性-添加新引用
操作:将路径中的libNetwork.vcxproj
加入项目,并根据上述位置添加新引用。
位置:项目-右键-属性-配置属性-链接器-输入-附加依赖项
操作:编辑 加入libcurl_imp.lib;libNetwork.lib;
cocos2d::extension::CCHttpRequest* request = new cocos2d::extension::CCHttpRequest();
设置url
request->setUrl("http://www.oschina.net/action/api/news_list");
设置请求类型
request->setRequestType(cocos2d::extension::CCHttpRequest::kHttpPost);
设置header
std::vector<std::string> headers;
headers.push_back("Content-Type: application/json; charset=utf-8");
request->setHeaders(headers);
设置请求的数据
const char* postData = "catalog=2&pageIndex=1&pageSize=5";
request->setRequestData(postData ,strlen(postData));
设置响应回调函数
request->setResponseCallback(this, callfuncND_selector(HelloWorld::onHttpRequestCompleted));
设置tag
request->setTag("Post_My_Data");
发送请求
cocos2d::extension::CCHttpClient::getInstance()->send(request);//添加请求到HttpClient任务队列
释放请求
request->release();//告诉HttpClient,我们已经完成了连接,并且它现在可以重用。如果不这样做的话,HttpClient将无限期地等待一个连接释放,以便它可以重用。
onHttpRequestCompleted(cocos2d::CCNode *sender ,void *data)
重定向输入输出流 //可缺
AllocConsole();//为调用进程分配一个新的控制台。
freopen("CONIN$", "r", stdin);//控制台输入
freopen("CONOUT$", "w", stdout);
freopen("CONOUT$", "w", stderr);
安全控制
cocos2d::extension::CCHttpResponse *response = (cocos2d::extension::CCHttpResponse*)data;
if (!response)
{
return;
}
if (0 != strlen(response->getHttpRequest()->getTag()))
{
CCLog("%s completed",response->getHttpRequest()->getTag());
}
检查状态码
int statusCode = response->getResponseCode();
char statusString[64] = {};
sprintf(statusString ,"Http status code:%d ,tag = %s" ,statusCode ,response->getHttpRequest()->getTag());
CCLog("response code:%d" ,statusCode);
if (!response->isSucceed())
{
CCLog("response failed");
CCLog("error buffer:%s" ,response->getErrorBuffer());
}
std::vector<char> *buffer = response->getResponseData();
向指定资源发出“显示”请求。仅用于读取数据。
HttpRequest* request = new HttpRequest();
request->setUrl("http://www.baidu.com");
request->setRequestType(HttpRequest::Type::GET);
request->setResponseCallback(CC_CALLBACK_2(HelloWorld::onHttpRequestCompleted,this));
request->setTag("GET test");
cocos2d::network::HttpClient::getInstance()->send(request);
request->release();
向指定资源提交数据,请求服务器进行处理。数据包含在请求文本中。
HttpRequest* request = new HttpRequest();
request->setUrl("httpbin.org/post");
request->setRequestType(HttpRequest::Type::POST);
request->setResponseCallback(CC_CALLBACK_2(HelloWorld::onHttpRequestCompleted,this));
// write the post data
const char* postData = "visitor=cocos2d&TestSuite=Extensions Test/NetworkTest";
request->setRequestData(postData, strlen(postData));
request->setTag("POST test");
cocos2d::network::HttpClient::getInstance()->send(request);
request->release();
1、Cocos2d-x之Http网络编程(一)——网络请求的发送和接收
2、如何使用HttpClient