Cocos2d HttpClient

h文件里面的内容


  1. #ifndef __LayerPaihan__  
  2. #define __LayerPaihan__  
  3.   
  4. #include "cocos2d.h"  
  5. #include "extensions/cocos-ext.h"  
  6. #include "network/HttpClient.h"  
  7.   
  8. USING_NS_CC;  
  9. USING_NS_CC_EXT;  
  10. using namespace network;  
  11.   
  12. class LayerPaihan : public cocos2d::LayerColor  
  13. {  
  14. public:  
  15.      virtual bool init();  
  16.      CREATE_FUNC(LayerPaihan);  
  17.        
  18.      //屏蔽下面的触摸事件  
  19.      EventListenerTouchOneByOne * listener;  
  20.      bool onTouchBegan(Touch* touch, Event* event);  
  21.      void menuClose(cocos2d::Ref* psender);  
  22.   
  23.   
  24.     void menuCloseCallback(cocos2d::Ref* pSender);  
  25.     void onMenuGetTestClicked(Ref* sender);  
  26.     void onMenuPostBinaryTestClicked(Ref* sender);  
  27.    // Http Response Callback  
  28.     void onHttpRequestCompleted(cocos2d::network::HttpClient *sender, cocos2d::network::HttpResponse *response);  
  29.   
  30.     Sprite* bg;  
  31. };  
  32.   
  33. #endif  
#ifndef __LayerPaihan__
#define __LayerPaihan__

#include "cocos2d.h"
#include "extensions/cocos-ext.h"
#include "network/HttpClient.h"

USING_NS_CC;
USING_NS_CC_EXT;
using namespace network;

class LayerPaihan : public cocos2d::LayerColor
{
public:
	 virtual bool init();
	 CREATE_FUNC(LayerPaihan);
	 
	 //屏蔽下面的触摸事件
	 EventListenerTouchOneByOne * listener;
	 bool onTouchBegan(Touch* touch, Event* event);
	 void menuClose(cocos2d::Ref* psender);


	void menuCloseCallback(cocos2d::Ref* pSender);
    void onMenuGetTestClicked(Ref* sender);
    void onMenuPostBinaryTestClicked(Ref* sender);
   // Http Response Callback
    void onHttpRequestCompleted(cocos2d::network::HttpClient *sender, cocos2d::network::HttpResponse *response);

	Sprite* bg;
};

#endif

.cpp里面的代码


  1. #include "LayerPaihan.h"  
  2. #include "json\rapidjson.h"  
  3. #include "json\document.h"  
  4. #include "json\stringbuffer.h"  
  5.   
  6. using namespace rapidjson;  
  7.   
  8.  bool LayerPaihan::init()  
  9.  {  
  10.      if(!LayerColor::initWithColor(Color4B(0,0,0,128))){  
  11.         return false;  
  12.      }  
  13.     Size visibleSize = Director::getInstance()->getVisibleSize();  
  14.     listener = EventListenerTouchOneByOne::create();    
  15.     listener->setSwallowTouches(true);   
  16.     listener->onTouchBegan = CC_CALLBACK_2(LayerPaihan::onTouchBegan, this);     
  17.     _eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this);  
  18.           
  19.     bg = Sprite::create("ph_bg.jpg");  
  20.     bg->setPosition(Point(visibleSize.width/2,visibleSize.height/2));  
  21.     this->addChild(bg);  
  22.   
  23.       
  24.   
  25.   
  26.     const int MARGIN = 40;  
  27.     const int SPACE = 70;  
  28.     auto menuRequest = Menu::create();  
  29.     menuRequest->setPosition(Point::ZERO);  
  30.     bg->addChild(menuRequest);  
  31.        
  32.     HttpRequest* request = new  HttpRequest();  
  33.     request->setUrl("http://127.0.0.1:8088/game/index.php");  
  34.     request->setRequestType(HttpRequest::Type::GET);  
  35.     request->setResponseCallback(this, httpresponse_selector(LayerPaihan::onHttpRequestCompleted));  
  36.     request->setTag("GET test1");  
  37.     HttpClient::getInstance()->send(request);  
  38.     request->release();  
  39.     
  40.    
  41.     auto close =MenuItemSprite::create(Sprite::createWithSpriteFrameName("x.png"),Sprite::createWithSpriteFrameName("x.png"),CC_CALLBACK_1(LayerPaihan::menuClose,this));  
  42.     close->setPosition(Point(bg->getContentSize().width,bg->getContentSize().height));  
  43.     auto menu = Menu::create(close, NULL);  
  44.     menu->setPosition(Vec2::ZERO);  
  45.     bg->addChild(menu,6);  
  46.   
  47.     return true;  
  48.  }  
  49.   
  50.  bool LayerPaihan::onTouchBegan(Touch* touch, Event* event){  
  51.      return true;  
  52.  }  
  53.   
  54.  void LayerPaihan::menuClose(cocos2d::Ref* psender){  
  55.     this->setVisible(false);  
  56.     listener->setSwallowTouches(false);  
  57.  }  
  58.   
  59.   
  60.  void LayerPaihan::onMenuGetTestClicked(Ref* sender)  
  61. {  
  62.     HttpRequest* request = new  HttpRequest();  
  63.     request->setUrl("http://127.0.0.1:8088/game/index.php");  
  64.     request->setRequestType(HttpRequest::Type::GET);  
  65.     request->setResponseCallback(this, httpresponse_selector(LayerPaihan::onHttpRequestCompleted));  
  66.     request->setTag("GET test1");  
  67.     HttpClient::getInstance()->send(request);  
  68.     request->release();  
  69. }  
  70.    
  71.    
  72. void LayerPaihan::onMenuPostBinaryTestClicked(cocos2d::Ref *sender)  
  73. {  
  74.     HttpRequest* request = new HttpRequest();  
  75.     request->setUrl("http://127.0.0.1:8088/game/index.php");  
  76.     request->setRequestType(HttpRequest::Type::POST);  
  77.     request->setResponseCallback(this, httpresponse_selector(LayerPaihan::onHttpRequestCompleted));  
  78.        
  79.        
  80.    const  char* postData = "params = Value";  
  81.     request->setRequestData(postData,strlen(postData) );  
  82.        
  83.        
  84.     request->setTag("POST test1");  
  85.     HttpClient::getInstance()->send(request);  
  86.     request->release();  
  87.        
  88.        
  89.        
  90.        
  91. }  
  92.    
  93. void LayerPaihan::onHttpRequestCompleted(cocos2d::network::HttpClient *sender, cocos2d::network::HttpResponse *response)  
  94. {  
  95.     if (!response) {  
  96.         return;  
  97.     }  
  98.     if (0 != strlen(response->getHttpRequest()->getTag())) {  
  99.         log("%s completed",response->getHttpRequest()->getTag());  
  100.     }  
  101.     long statusCode = response->getResponseCode();  
  102.     char statusString[64] = {};  
  103.        
  104.     if (!response->isSucceed()) {  
  105.         log("response failed");  
  106.         log("error buffer: %s",response->getErrorBuffer());  
  107.         return;  
  108.     }     
  109.   
  110.     std::vector<char>* buffer = response->getResponseData();  
  111.     std::stringstream oss;   
  112.     for(unsigned int i=0;i < buffer->size();i++){   
  113.         oss<<(*buffer)[i];   
  114.     }   
  115.   
  116.     std::string temp=oss.str();   
  117.     const char * buf=temp.c_str();   
  118.     rapidjson::Document doc;  
  119.     doc.Parse<0>(buf);//<通过Parse方法将Json数据解析出来  
  120.     if(doc.HasParseError())  
  121.     {  
  122.         CCLOG("GetParseError%s\n",doc.GetParseError());  
  123.     }  
  124.     if(doc.IsArray())///<判断是否是字符串  
  125.     {  
  126.          for (unsigned int i = 0; i< doc.Size(); ++i) {  
  127.                  const rapidjson::Value &index = doc[i]["index"];  
  128.                  const rapidjson::Value &name = doc[i]["name"];  
  129.                  const rapidjson::Value &gold = doc[i]["gold"];  
  130.                  auto xs = Label::createWithSystemFont(index.GetString(),"Microsoft YaHei",18);  
  131.                  xs->setAnchorPoint(Point(0,0));  
  132.                  xs->setPosition(Point(200,244-i*30));  
  133.                  bg->addChild(xs);  
  134.                  auto xs_name = Label::createWithSystemFont(name.GetString(),"Microsoft YaHei",18);  
  135.                  xs_name->setAnchorPoint(Point(0,0));  
  136.                  xs_name->setPosition(Point(310,244-i*30));  
  137.                  bg->addChild(xs_name);  
  138.                  auto xs_gold = Label::createWithSystemFont(gold.GetString(),"Microsoft YaHei",18);  
  139.                  xs_gold->setAnchorPoint(Point(0,0));  
  140.                  xs_gold->setPosition(Point(440,244-i*30));  
  141.                  bg->addChild(xs_gold);  
  142.   
  143.          }  
  144.           
  145.     }  
  146.   
  147. }  
#include "LayerPaihan.h"
#include "json\rapidjson.h"
#include "json\document.h"
#include "json\stringbuffer.h"

using namespace rapidjson;

 bool LayerPaihan::init()
 {
	 if(!LayerColor::initWithColor(Color4B(0,0,0,128))){
		return false;
	 }
	Size visibleSize = Director::getInstance()->getVisibleSize();
	listener = EventListenerTouchOneByOne::create();  
    listener->setSwallowTouches(true); 
    listener->onTouchBegan = CC_CALLBACK_2(LayerPaihan::onTouchBegan, this);   
    _eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this);
		
	bg = Sprite::create("ph_bg.jpg");
	bg->setPosition(Point(visibleSize.width/2,visibleSize.height/2));
	this->addChild(bg);

	


	const int MARGIN = 40;
    const int SPACE = 70;
	auto menuRequest = Menu::create();
    menuRequest->setPosition(Point::ZERO);
    bg->addChild(menuRequest);
     
    HttpRequest* request = new  HttpRequest();
    request->setUrl("http://127.0.0.1:8088/game/index.php");
    request->setRequestType(HttpRequest::Type::GET);
    request->setResponseCallback(this, httpresponse_selector(LayerPaihan::onHttpRequestCompleted));
    request->setTag("GET test1");
    HttpClient::getInstance()->send(request);
    request->release();
  
 
	auto close =MenuItemSprite::create(Sprite::createWithSpriteFrameName("x.png"),Sprite::createWithSpriteFrameName("x.png"),CC_CALLBACK_1(LayerPaihan::menuClose,this));
	close->setPosition(Point(bg->getContentSize().width,bg->getContentSize().height));
	auto menu = Menu::create(close, NULL);
    menu->setPosition(Vec2::ZERO);
	bg->addChild(menu,6);

	return true;
 }

 bool LayerPaihan::onTouchBegan(Touch* touch, Event* event){
	 return true;
 }

 void LayerPaihan::menuClose(cocos2d::Ref* psender){
	this->setVisible(false);
	listener->setSwallowTouches(false);
 }


 void LayerPaihan::onMenuGetTestClicked(Ref* sender)
{
    HttpRequest* request = new  HttpRequest();
    request->setUrl("http://127.0.0.1:8088/game/index.php");
    request->setRequestType(HttpRequest::Type::GET);
    request->setResponseCallback(this, httpresponse_selector(LayerPaihan::onHttpRequestCompleted));
    request->setTag("GET test1");
    HttpClient::getInstance()->send(request);
    request->release();
}
 
 
void LayerPaihan::onMenuPostBinaryTestClicked(cocos2d::Ref *sender)
{
    HttpRequest* request = new HttpRequest();
    request->setUrl("http://127.0.0.1:8088/game/index.php");
    request->setRequestType(HttpRequest::Type::POST);
    request->setResponseCallback(this, httpresponse_selector(LayerPaihan::onHttpRequestCompleted));
     
     
   const  char* postData = "params = Value";
    request->setRequestData(postData,strlen(postData) );
     
     
    request->setTag("POST test1");
    HttpClient::getInstance()->send(request);
    request->release();
     
     
     
     
}
 
void LayerPaihan::onHttpRequestCompleted(cocos2d::network::HttpClient *sender, cocos2d::network::HttpResponse *response)
{
    if (!response) {
        return;
    }
    if (0 != strlen(response->getHttpRequest()->getTag())) {
        log("%s completed",response->getHttpRequest()->getTag());
    }
    long statusCode = response->getResponseCode();
    char statusString[64] = {};
     
    if (!response->isSucceed()) {
        log("response failed");
        log("error buffer: %s",response->getErrorBuffer());
        return;
    }	

    std::vector<char>* buffer = response->getResponseData();
	std::stringstream oss; 
	for(unsigned int i=0;i < buffer->size();i++){ 
		oss<<(*buffer)[i]; 
	} 

	std::string temp=oss.str(); 
	const char * buf=temp.c_str(); 
	rapidjson::Document doc;
	doc.Parse<0>(buf);//<通过Parse方法将Json数据解析出来
	if(doc.HasParseError())
	{
		CCLOG("GetParseError%s\n",doc.GetParseError());
	}
	if(doc.IsArray())///<判断是否是字符串
	{
		 for (unsigned int i = 0; i< doc.Size(); ++i) {
				 const rapidjson::Value &index = doc[i]["index"];
                 const rapidjson::Value &name = doc[i]["name"];
				 const rapidjson::Value &gold = doc[i]["gold"];
				 auto xs = Label::createWithSystemFont(index.GetString(),"Microsoft YaHei",18);
				 xs->setAnchorPoint(Point(0,0));
				 xs->setPosition(Point(200,244-i*30));
				 bg->addChild(xs);
				 auto xs_name = Label::createWithSystemFont(name.GetString(),"Microsoft YaHei",18);
				 xs_name->setAnchorPoint(Point(0,0));
				 xs_name->setPosition(Point(310,244-i*30));
				 bg->addChild(xs_name);
				 auto xs_gold = Label::createWithSystemFont(gold.GetString(),"Microsoft YaHei",18);
				 xs_gold->setAnchorPoint(Point(0,0));
				 xs_gold->setPosition(Point(440,244-i*30));
				 bg->addChild(xs_gold);

         }
		
	}

}



介绍

HttpClient是HTTP客户端的接口。HttpClient封装了各种对象,处理cookies,身份认证,连接管理等。

概念

HttpClient的使用一般包含下面6个步骤:

  • 创建 HttpRequest 的实例;
  • 设置某种连接方法的类型(GET、POST等),这里通过setUrl传入待连接的地址;
  • 设置响应回调函数,读取response;
  • 添加请求到HttpClient任务队列;
  • 释放连接。无论执行方法是否成功,都必须释放连接;
  • 对得到后的内容进行处理。

如何使用

引入头文件和命名空间

#include "network/HttpClient.h"
using namespace cocos2d::network;

HttpRequest 实例

我们将使用HttpRequest无参数的构造函数,它为大多数情况提供了一个很好的默认设置,所以我们使用它。

HttpRequest* request = new HttpRequest();

设置连接方法的类型和待连接的地址

由HTTP规范定义的各种方法对应各种不同的HttpRequest类。

我们将使用Get方法,这是一个简单的方法,它只是简单地取得一个URL,获取URL指向的文档。

request->setRequestType(HttpRequest::Type::GET);
request->setUrl("http://www.httpbin.org/get");

设置回调

无论服务器返回怎样的状态,响应主体response body总是可读的,这至关重要。

request->setResponseCallback(CC_CALLBACK_2(HelloWorld::onHttpComplete,this));

在onHttpComplete里读取响应数据:

std::vector<char> *buffer = response->getResponseData();//Get the request data pointer back

添加请求到HttpClient任务队列

cocos2d::network::HttpClient::getInstance()->send(request);

释放连接

这是一个可以让整个流程变得完整的关键步骤, 我们必须告诉HttpClient,我们已经完成了连接,并且它现在可以重用。如果不这样做的话,HttpClient将无限期地等待一个连接释放,以便它可以重用。

要释放连接,使用:

request->release();

处理响应

现在,我们已经完成了与HttpClient的交互,可以集中精力做我们需要处理的数据。在这个例子中,我们仅仅将它在控制台上输出。

// dump data
std::vector *buffer = response->getResponseData();
printf("Http Test, dump data: ");
for (unsigned int i = 0; i < buffer->size(); i++)
{
    printf("%c", (*buffer)[i]);
}
printf("\n");

如果你需要把response作为一个流来读取它里面的信息,上面的步骤将会同如何解析这个连接结合,当你处理完所有的数据后,关闭输入流,并释放该连接。

GET请求示例

下面是一个通过HttpClient的HTTP GET请求的例子。

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

POST请求示例

下面将发送一个POST请求到URL“http://httpbin.org/post”。

    HttpRequest* request = new HttpRequest();
    request->setUrl("http://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();

处理网络回调函数

void HelloWorld::onHttpRequestCompleted(HttpClient *sender, HttpResponse *response)
{
    if (!response)
    {
        return;
    }   

    // You can get original request type from: response->request->reqType
    if (0 != strlen(response->getHttpRequest()->getTag()))
    {
        log("%s completed", response->getHttpRequest()->getTag());
    }   
    int statusCode = response->getResponseCode();
    char statusString[64] = {};
    sprintf(statusString, "HTTP Status Code: %d, tag = %s", statusCode, response->getHttpRequest()->getTag());
    _labelStatusCode->setString(statusString);
    log("response code: %d", statusCode);   
    if (!response->isSucceed())
    {
        log("response failed");
        log("error buffer: %s", response->getErrorBuffer());
        return;
    }
    // dump data
    std::vector<char> *buffer = response->getResponseData();
    printf("Http Test, dump data: ");
    for (unsigned int i = 0; i < buffer->size(); i++)
    {
        printf("%c", (*buffer)[i]);
    }
    printf("\n");
}

Android

需要注意的是,如果你是Android环境,不要忘了在您的应用程序的Manifest 中增加相应的权限:

<uses-permission android:name=”android.permission.INTERNET” />

详细代码可参照..\tests\Cpp\TestCpp\Classes\ExtensionsTest\NetworkTest\HttpClientTest.cpp




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值