HTTP Header详解 cocos2d-x django http CCHttpRequest
HTTP Cookie
Cookie相关的Http头
Set-Cookie Header
在程序中生成expire
Set-Cookie Header
在程序中生成expire
Cookie相关的Http头
有连个Http头部和Cookie有关:Set-Cookie和Cookie。
Set-Cookie由服务器发送,它包含在响应请求的头部中。它用于在客户端创建一个Cookie
Cookie头由客户端发送,包含在HTTP请求的头部中。注意,只有cookie的domain和path与请求的URL匹配才会发送这个cookie。
Set-Cookie Header
Set-Cookie响应头的格式如下所示:
Set-Cookie: <name>=<value>[; <name>=<value>]...
[; expires=<date>][; domain=<domain_name>]
[; path=<some_path>][; secure][; httponly]
expires=<date>: 设置cookie的有效期,如果cookie超过date所表示的日期时,cookie将失效。
如果没有设置这个选项,那么cookie将在浏览器关闭时失效。
注意:date是格林威治时间(GMT),使用如下格式表示:
DAY, DD MMM YYYY HH:MM:SS GMT
DAY
The day of the week (Sun, Mon, Tue, Wed, Thu, Fri, Sat).
DD
The day in the month (such as 01 for the first day of the month).
MMM
The three-letter abbreviation for the month (Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec).
YYYY
The year.
HH
The hour value in military time (22 would be 10:00 P.M., for example).
MM
The minute value.
SS
The second value.
domain=<domain_name> :
path=<some_path>:
注:临时cookie(没有expires参数的cookie)不能带有domain选项。
当客户端发送一个http请求时,会将有效的cookie一起发送给服务器。
如果一个cookie的domain和path参数和URL匹配,那么这个cookie就是有效的。
一个URL中包含有domain和path,可以参考http://www.w3school.com.cn/html/html_url.asp
secure : 表示cookie只能被发送到http服务器。
httponly : 表示cookie不能被客户端脚本获取到。
在程序中生成expires
C的方式
time_t curTime = time(NULL);
tm * gmTime = gmtime(&curTime);
char strExperis[50];
strftime(strTimeBuf, 100, " %a, %d %b %Y %X GMT;", gmTime);
JavaScript的方式
var d = new Date();
var expires = d.toGMTString();
cocos2d-x模拟浏览器
ckLoginUILapyer.h文件
#ifndef __CK_LOGIN_UILAYER__H__ #define __CK_LOGIN_UILAYER__H__ #include "cocos2d.h" #include "cocos-ext.h" #define CK_LOGIN_UILAYER_UIHIDE_TAG 1 #define CK_LOGIN_UILAYER_UISHOW_TAG 10 using namespace cocos2d; using namespace cocos2d::extension; class ckLoginUILayer: public cocos2d::extension::UILayer,public cocos2d::extension::CCTableViewDataSource, public cocos2d::extension::CCTableViewDelegate { public: static ckLoginUILayer * create(); virtual bool init(); void loginByAccountCallBack(CCObject * pSender); void loginGameCallBack(CCObject * pSender); void quitGameCallBack(CCObject * pSender); //add by yx void onGetFinished(CCNode *node,void *data); void onGetFinished1(CCNode *node,void *data); //end-add by yx void ShowFirstUI(bool b = true); void HideFirstUI(); void ShowAccountLogin(bool b = true); void HideAccountLogin(); virtual void scrollViewDidScroll(cocos2d::extension::CCScrollView* view) {}; virtual void scrollViewDidZoom(cocos2d::extension::CCScrollView* view){}; virtual void tableCellTouched(cocos2d::extension::CCTableView* table, cocos2d::extension::CCTableViewCell* cell); virtual cocos2d::CCSize cellSizeForTable(cocos2d::extension::CCTableView *table); virtual cocos2d::extension::CCTableViewCell* tableCellAtIndex(cocos2d::extension::CCTableView *table, unsigned int idx); virtual unsigned int numberOfCellsInTableView(cocos2d::extension::CCTableView *table); private: UIWidget *m_firstUI; //从logo切换过来的第一个界面 UIWidget *m_accountLogin; // 账号输入登陆界面 UIWidget *m_guestCreateRole; // 未注册账号登陆后创建角色界面,使用IMEI相关 UIWidget *m_addRoleInfo; // 完善账号信息界面,针对使用IMEI玩,类似绑定一个账号 UIWidget *m_settingUI; // 用户以及相关设置 UIWidget *m_changeServerPromptUI; // 更改服务器的提示界面 UIWidget *m_createRoleUI; // 创建一个新的角色 UIWidget *m_serverListUI; // 显示服务器列表以及相关 UIWidget *m_roleSelectUI; // 选择已有角色界面 }; #endif
ckLoginUILapyer.cpp 文件
#include "ckLoginUILayer.h" #include <curl/curl.h> #include ckLoginUILayer * ckLoginUILayer::create() { ckLoginUILayer * pRet = new ckLoginUILayer(); if(pRet && pRet->init()) { pRet->autorelease(); return pRet; } else { CC_SAFE_DELETE(pRet); return NULL; } } void ckLoginUILayer::onGetFinished(CCNode *node,void *data){ CCHttpResponse *response = (CCHttpResponse*)data; if (!response) { return; } int s=response->getHttpRequest()->getRequestType(); CCLOG("request type %d",s); if (0 != strlen(response->getHttpRequest()->getTag())) { CCLOG("%s ------>oked", response->getHttpRequest()->getTag()); } int statusCode = response->getResponseCode(); CCLOG("response code: %d", statusCode); char statusString[64] = {}; CCLOG("HTTP Status Code: %d, tag = %s", statusCode, response->getHttpRequest()->getTag()); CCLOG(statusString); if (!response->isSucceed()) { CCLOG("response failed"); CCLOG("error buffer: %s", response->getErrorBuffer()); return; } std::vector *buffer = response->getResponseData(); CCLOG("Http Test, dump data: "); for (unsigned int i = 0; i < buffer->size(); i++) { CCLOG("%c", (*buffer)[i]);//这里打印从服务器返回的数据 } std::vector *buffer0 = response->getResponseHeader(); //寻找sessionid---重要 //std::string sss; std::string sessionid; CCLOG("header: "); for (unsigned int i = 0; i < buffer0->size(); i++) { sessionid += (*buffer0)[i]; //sss += (*buffer0)[i]; } CCLOG("%s", sessionid.c_str()); int pos = sessionid.find("sessionid"); int endpos = sessionid.find(';',pos); sessionid = sessionid.substr(pos,endpos - pos+1); sessionid = "Cookie: "+sessionid+" httponly; Path=/"; CCLOG("%s", sessionid.c_str()); CCLOG("\n"); //end---寻找sessionid CCHttpRequest* request = response->getHttpRequest(); //设置cookie--重要 std::vector headers; headers.push_back("Connection: Keep-Alive"); headers.push_back(sessionid.c_str()); //headers.push_back("Set-Cookie: sessionid=2jpu2ht1opllifaps3xnzp92y6f60skd; httponly; Path=/"); request->setHeaders(headers); //end--设置cookie--重要 request->setResponseCallback(this, callfuncND_selector(ckLoginUILayer::onGetFinished1)); const char* postData = "p={'m':1}"; request->setRequestData(postData, strlen(postData)); request->setTag("POST test2"); CCHttpClient::getInstance()->send(request); request->retain(); request->release(); } void ckLoginUILayer::onGetFinished1(CCNode *node,void *data){ CCHttpResponse *response = (CCHttpResponse*)data; if (!response) { return; } int s=response->getHttpRequest()->getRequestType(); CCLOG("request type %d",s); if (0 != strlen(response->getHttpRequest()->getTag())) { CCLOG("%s ------>oked", response->getHttpRequest()->getTag()); } int statusCode = response->getResponseCode(); CCLOG("response code: %d", statusCode); char statusString[64] = {}; CCLOG("HTTP Status Code: %d, tag = %s", statusCode, response->getHttpRequest()->getTag()); CCLOG(statusString); if (!response->isSucceed()) { CCLOG("response failed"); CCLOG("error buffer: %s", response->getErrorBuffer()); return; } std::vector *buffer = response->getResponseData(); CCLOG("Http Test, dump data: "); for (unsigned int i = 0; i < buffer->size(); i++) { CCLOG("%c", (*buffer)[i]);//这里打印从服务器返回的数据 } std::vector *buffer0 = response->getResponseHeader(); std::string sss; CCLOG("header: "); for (unsigned int i = 0; i < buffer0->size(); i++) { //CCLog("%c", (*buffer)[i]);//这里打印从服务器返回的数据 sss += (*buffer0)[i]; } CCLOG("%s", sss.c_str()); CCLOG("\n"); } bool ckLoginUILayer::init() { //add by yx CCHttpRequest* request = new CCHttpRequest(); request->setUrl("http://127.0.0.1:8008/msg"); request->setRequestType(CCHttpRequest::kHttpPost); std::vector headers; //headers.push_back("Set-Cookie: sessionid=9gs0ndxirl86y3my6bxl3zl9b3dqj4a5; path=/"); //WebServer当中数据文件头类型说明 ;Cookie: sessionid=9gs0ndxirl86y3my6bxl3zl9b3dqj4a5 headers.push_back("Connection: Keep-Alive"); request->setHeaders(headers); request->setResponseCallback(this, callfuncND_selector(ckLoginUILayer::onGetFinished)); const char* postData = "p={'m':2,'i':'123'}"; request->setRequestData(postData, strlen(postData)); request->setTag("POST test1"); CCHttpClient::getInstance()->send(request); request->release(); //end--add by yx if(!UILayer::init()) return false; CCPoint centerPoint = ccp(this->getContentSize().width/2, this->getContentSize().height/2); // init UIWidget *rootW = dynamic_cast<UIWidget*>(CCUIHELPER->createWidgetFromJsonFile("Loginsystem_1.json")); this->addWidget(rootW); m_firstUI = dynamic_cast<UIWidget*>(rootW->getChildByTag(2)); m_firstUI->setAnchorPoint(ccp(0.5, 0.5)); m_firstUI->setPosition(centerPoint); UIButton *inputAccount = dynamic_cast<UIButton*>(m_firstUI->getChildByName("For_Account")); inputAccount->addReleaseEvent(this, coco_releaseselector(ckLoginUILayer::loginByAccountCallBack)); ShowFirstUI(); m_accountLogin = dynamic_cast<UIWidget*>(rootW->getChildByTag(14)); m_accountLogin->setAnchorPoint(ccp(0.5, 0.5)); m_accountLogin->setPosition(centerPoint); UIButton *loginGame = dynamic_cast<UIButton*>(m_accountLogin->getChildByName("Oa_Login")); loginGame->addReleaseEvent(this, coco_releaseselector(ckLoginUILayer::loginGameCallBack)); UIButton *quitGame = dynamic_cast<UIButton*>(m_accountLogin->getChildByName("Oa_Quit")); quitGame->addReleaseEvent(this, coco_releaseselector(ckLoginUILayer::quitGameCallBack)); HideAccountLogin(); m_guestCreateRole = dynamic_cast<UIWidget*>(rootW->getChildByTag(17)); m_guestCreateRole->setAnchorPoint(ccp(0.5, 0.5)); m_guestCreateRole->setPosition(centerPoint); CCSize winSize = CCDirector::sharedDirector()->getWinSize(); CCTableView* tableView = CCTableView::create(this, CCSizeMake(160, 250)); tableView->setDirection(kCCScrollViewDirectionVertical); tableView->setPosition(ccp(20,winSize.height/2-30)); tableView->setDelegate(this); this->addChild(tableView); tableView->reloadData(); } void ckLoginUILayer::tableCellTouched(cocos2d::extension::CCTableView* table, cocos2d::extension::CCTableViewCell* cell) { // } cocos2d::CCSize ckLoginUILayer::cellSizeForTable(cocos2d::extension::CCTableView *table) { return CCSizeMake(160, 30); } cocos2d::extension::CCTableViewCell* ckLoginUILayer::tableCellAtIndex(cocos2d::extension::CCTableView *table, unsigned int idx) { CCString *string = CCString::createWithFormat("Hello %d",idx); CCTableViewCell *cell = table->dequeueCell(); if(!cell) { cell = new CCTableViewCell(); cell->autorelease(); CCLabelTTF *label = CCLabelTTF::create(string->getCString(), "Helvetica", 30.0); label->setPosition(CCPointZero); label->setAnchorPoint(CCPointZero); label->setTag(123); cell->addChild(label); } else { CCLabelTTF *label = (CCLabelTTF*)cell->getChildByTag(123); label->setString(string->getCString()); } return cell; } unsigned int ckLoginUILayer::numberOfCellsInTableView(cocos2d::extension::CCTableView *table) { return 50; } void ckLoginUILayer::loginByAccountCallBack(CCObject * pSender) { if(m_firstUI->isVisible()) HideFirstUI(); ShowAccountLogin(); } void ckLoginUILayer::loginGameCallBack(CCObject * pSender) { } void ckLoginUILayer::quitGameCallBack(CCObject * pSender) { #if (CC_TARGET_PLATFORM == CC_PLATFORM_WINRT) || (CC_TARGET_PLATFORM == CC_PLATFORM_WP8) CCMessageBox("You pressed the close button. Windows Store Apps do not implement a close button.","Alert"); #else CCDirector::sharedDirector()->end(); #if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS) exit(0); #endif #endif } void ckLoginUILayer::ShowFirstUI(bool b/* = true*/) { if(m_firstUI) { m_firstUI->setVisible(b); m_firstUI->getChildByTag(102)->setTouchEnabled(b); if(b) { m_firstUI->setZOrder(CK_LOGIN_UILAYER_UISHOW_TAG); m_firstUI->getChildByTag(102)->setZOrder(CK_LOGIN_UILAYER_UISHOW_TAG); } else { m_firstUI->setZOrder(CK_LOGIN_UILAYER_UIHIDE_TAG); m_firstUI->getChildByTag(102)->setZOrder(CK_LOGIN_UILAYER_UIHIDE_TAG); } } } void ckLoginUILayer::HideFirstUI() { ShowFirstUI(false); } void ckLoginUILayer::ShowAccountLogin(bool b/* = true*/) { if(m_accountLogin) { m_accountLogin->setVisible(b); m_accountLogin->getChildByTag(14)->setTouchEnabled(b); m_accountLogin->getChildByTag(8)->setTouchEnabled(b); m_accountLogin->getChildByTag(15)->setTouchEnabled(b); m_accountLogin->getChildByTag(16)->setTouchEnabled(b); if(b) { m_accountLogin->setZOrder(CK_LOGIN_UILAYER_UISHOW_TAG); m_accountLogin->getChildByTag(14)->setZOrder(CK_LOGIN_UILAYER_UISHOW_TAG); m_accountLogin->getChildByTag(8)->setZOrder(CK_LOGIN_UILAYER_UISHOW_TAG); m_accountLogin->getChildByTag(15)->setZOrder(CK_LOGIN_UILAYER_UISHOW_TAG); m_accountLogin->getChildByTag(16)->setZOrder(CK_LOGIN_UILAYER_UISHOW_TAG); } else { m_accountLogin->setZOrder(CK_LOGIN_UILAYER_UIHIDE_TAG); m_accountLogin->getChildByTag(14)->setZOrder(CK_LOGIN_UILAYER_UIHIDE_TAG); m_accountLogin->getChildByTag(8)->setZOrder(CK_LOGIN_UILAYER_UIHIDE_TAG); m_accountLogin->getChildByTag(15)->setZOrder(CK_LOGIN_UILAYER_UIHIDE_TAG); m_accountLogin->getChildByTag(16)->setZOrder(CK_LOGIN_UILAYER_UIHIDE_TAG); } } } void ckLoginUILayer::HideAccountLogin() { ShowAccountLogin(false); }