Merge pull request #1163 from dumganhar/network

fixed #1424: add a simple wrapper of http access
This commit is contained in:
James Chen 2012-08-09 02:09:15 -07:00
commit ff2a9ccbd7
24 changed files with 1316 additions and 55 deletions

View File

@ -93,6 +93,9 @@ Developers:
Nat Weiss
Minor enhancements to the Cocos2D-X codebase and Android build scripts
Qingyun Huang (greathqy)
implement CCHttpRequest
Retired Core Developers:
WenSheng Yang
Author of windows port, CCTextField,

View File

@ -154,7 +154,6 @@ LOCAL_WHOLE_STATIC_LIBRARIES += cocos_jpeg_static
LOCAL_WHOLE_STATIC_LIBRARIES += cocos_libxml2_static
LOCAL_WHOLE_STATIC_LIBRARIES += cocos_libtiff_static
# define the macro to compile through support/zip_support/ioapi.c
LOCAL_CFLAGS := -DUSE_FILE32API
@ -164,4 +163,3 @@ $(call import-module,libjpeg)
$(call import-module,libpng)
$(call import-module,libxml2)
$(call import-module,libtiff)

View File

@ -317,7 +317,7 @@ CCAction* CCActionManager::getActionByTag(unsigned int tag, CCObject *pTarget)
}
else
{
CCLOG("cocos2d : getActionByTag: Target not found");
// CCLOG("cocos2d : getActionByTag: Target not found");
}
return NULL;

View File

@ -1,7 +1,7 @@
LOCAL_PATH := $(call my-dir)
include $(CLEAR_VARS)
LOCAL_MODULE := curl_static_prebuilt
LOCAL_MODULE := cocos_curl_static
LOCAL_MODULE_FILENAME := curl
LOCAL_SRC_FILES := libs/$(TARGET_ARCH_ABI)/libcurl.a
LOCAL_EXPORT_C_INCLUDES := $(LOCAL_PATH)/include

View File

@ -17,12 +17,14 @@ INCLUDES = -I.. \
-I../../extensions/CCBReader \
-I../../extensions/GUI/CCControlExtension \
-I../../extensions/GUI/CCControlExtension \
-I../../extensions/network \
-I../platform/linux/ \
-I../platform/third_party/linux/glew-1.7.0/glew-1.7.0/include/ \
-I../platform/third_party/linux/libxml2 \
-I../platform/third_party/linux/libpng \
-I../platform/third_party/linux/libjpeg \
-I../platform/third_party/linux/libtiff/include \
-I../platform/third_party/linux/ \
# -I../platform/third_party/linux/libpng \
@ -155,6 +157,7 @@ OBJECTS = ../actions/CCAction.o \
../../extensions/GUI/CCControlExtension/CCMenuPassive.o \
../../extensions/GUI/CCControlExtension/CCScale9Sprite.o \
../../extensions/GUI/CCControlExtension/CCSpacer.o \
../../extensions/network/HttpClient.o \
../kazmath/src/aabb.o \
../kazmath/src/plane.o \
../kazmath/src/vec2.o \

View File

@ -34,16 +34,19 @@ GUI/CCControlExtension/CCInvocation.cpp \
GUI/CCControlExtension/CCMenuPassive.cpp \
GUI/CCControlExtension/CCScale9Sprite.cpp \
GUI/CCControlExtension/CCSpacer.cpp \
GUI/CCScrollView/CCScrollView.cpp
GUI/CCScrollView/CCScrollView.cpp \
network/HttpClient.cpp
LOCAL_WHOLE_STATIC_LIBRARIES := cocos2dx_static
LOCAL_WHOLE_STATIC_LIBRARIES += cocos_curl_static
LOCAL_EXPORT_C_INCLUDES := $(LOCAL_PATH) \
$(LOCAL_PATH)/CCBReader \
$(LOCAL_PATH)/UI/CCControlExtension \
$(LOCAL_PATH)/UI/CCScrollView
$(LOCAL_PATH)/GUI/CCControlExtension \
$(LOCAL_PATH)/GUI/CCScrollView \
$(LOCAL_PATH)/network
include $(BUILD_STATIC_LIBRARY)
$(call import-module,cocos2dx)
$(call import-module,cocos2dx/platform/third_party/android/prebuilt/libcurl)

View File

@ -28,5 +28,9 @@
#include "GUI/CCControlExtension/CCControlExtensions.h"
#include "GUI/CCScrollView/CCScrollView.h"
#include "network/HttpRequest.h"
#include "network/HttpResponse.h"
#include "network/HttpClient.h"
#endif /* __COCOS2D_EXT_H__ */

View File

@ -0,0 +1,481 @@
/****************************************************************************
Copyright (c) 2010-2012 cocos2d-x.org
Copyright (c) 2012 greathqy
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
#include "HttpClient.h"
// #include "platform/CCThread.h"
#include <queue>
#include <pthread.h>
#include <semaphore.h>
#include <errno.h>
#include "curl/curl.h"
NS_CC_EXT_BEGIN
static pthread_t s_networkThread;
static pthread_mutex_t s_requestQueueMutex;
static pthread_mutex_t s_responseQueueMutex;
static sem_t * s_pSem = NULL;
static unsigned long s_asyncRequestCount = 0;
#if CC_TARGET_PLATFORM == CC_PLATFORM_IOS
#define CC_ASYNC_HTTPREQUEST_USE_NAMED_SEMAPHORE 1
#else
#define CC_ASYNC_HTTPREQUEST_USE_NAMED_SEMAPHORE 0
#endif
#if CC_ASYNC_HTTPREQUEST_USE_NAMED_SEMAPHORE
#define CC_ASYNC_HTTPREQUEST_SEMAPHORE "ccHttpAsync"
#else
static sem_t s_sem;
#endif
#if (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32)
typedef int int32_t;
#endif
static bool need_quit = false;
static CCArray* s_requestQueue = NULL;
static CCArray* s_responseQueue = NULL;
static CCHttpClient *s_pHttpClient = NULL; // pointer to singleton
static char s_errorBuffer[CURL_ERROR_SIZE];
typedef size_t (*write_callback)(void *ptr, size_t size, size_t nmemb, void *stream);
// Callback function used by libcurl for collect response data
size_t writeData(void *ptr, size_t size, size_t nmemb, void *stream)
{
std::vector<char> *recvBuffer = (std::vector<char>*)stream;
size_t sizes = size * nmemb;
recvBuffer->clear();
recvBuffer->assign((char*)ptr, (char*)ptr + sizes);
return sizes;
}
// Prototypes
bool configureCURL(CURL *handle);
int processGetTask(CCHttpRequest *request, write_callback callback, void *stream, int32_t *errorCode);
int processPostTask(CCHttpRequest *request, write_callback callback, void *stream, int32_t *errorCode);
// int processDownloadTask(HttpRequest *task, write_callback callback, void *stream, int32_t *errorCode);
// Worker thread
static void* networkThread(void *data)
{
CCHttpRequest *request = NULL;
while (true)
{
// Wait for http request tasks from main thread
int semWaitRet = sem_wait(s_pSem);
if (semWaitRet < 0) {
CCLog("HttpRequest async thread semaphore error: %s\n", strerror(errno));
break;
}
if (need_quit)
{
break;
}
// step 1: send http request if the requestQueue isn't empty
request = NULL;
pthread_mutex_lock(&s_requestQueueMutex); //Get request task from queue
if (0 != s_requestQueue->count())
{
request = dynamic_cast<CCHttpRequest*>(s_requestQueue->objectAtIndex(0));
s_requestQueue->removeObjectAtIndex(0);
// request's refcount = 1 here
}
pthread_mutex_unlock(&s_requestQueueMutex);
if (NULL == request)
{
continue;
}
// step 2: libcurl sync access
// Create a HttpResponse object, the default setting is http access failed
CCHttpResponse *response = new CCHttpResponse(request);
// request's refcount = 2 here, it's retained by HttpRespose constructor
request->release();
// ok, refcount = 1 now, only HttpResponse hold it.
int responseCode = -1;
int retValue = 0;
// Process the request -> get response packet
switch (request->getRequestType())
{
case CCHttpRequest::kHttpGet: // HTTP GET
retValue = processGetTask(request,
writeData,
response->getResponseData(),
&responseCode);
break;
case CCHttpRequest::kHttpPost: // HTTP POST
retValue = processPostTask(request,
writeData,
response->getResponseData(),
&responseCode);
break;
default:
CCAssert(true, "CCHttpClient: unkown request type, only GET and POSt are supported");
break;
}
// write data to HttpResponse
response->setResponseCode(responseCode);
if (retValue != 0)
{
response->setSucceed(false);
response->setErrorBuffer(s_errorBuffer);
}
else
{
response->setSucceed(true);
}
// add response packet into queue
pthread_mutex_lock(&s_responseQueueMutex);
s_responseQueue->addObject(response);
pthread_mutex_unlock(&s_responseQueueMutex);
// resume dispatcher selector
CCDirector::sharedDirector()->getScheduler()->resumeTarget(CCHttpClient::getInstance());
}
// cleanup: if worker thread received quit signal, clean up un-completed request queue
pthread_mutex_lock(&s_requestQueueMutex);
s_requestQueue->removeAllObjects();
pthread_mutex_unlock(&s_requestQueueMutex);
s_asyncRequestCount -= s_requestQueue->count();
if (s_pSem != NULL) {
#if CC_ASYNC_HTTPREQUEST_USE_NAMED_SEMAPHORE
sem_unlink(CC_ASYNC_HTTPREQUEST_SEMAPHORE);
sem_close(s_pSem);
#else
sem_destroy(s_pSem);
#endif
s_pSem = NULL;
pthread_mutex_destroy(&s_requestQueueMutex);
pthread_mutex_destroy(&s_responseQueueMutex);
s_requestQueue->release();
s_responseQueue->release();
}
pthread_exit(NULL);
return 0;
}
//Configure curl's timeout property
bool configureCURL(CURL *handle)
{
if (!handle) {
return false;
}
int32_t code;
code = curl_easy_setopt(handle, CURLOPT_ERRORBUFFER, s_errorBuffer);
if (code != CURLE_OK) {
return false;
}
code = curl_easy_setopt(handle, CURLOPT_TIMEOUT, CCHttpClient::getInstance()->getTimeoutForRead());
if (code != CURLE_OK) {
return false;
}
code = curl_easy_setopt(handle, CURLOPT_CONNECTTIMEOUT, CCHttpClient::getInstance()->getTimeoutForConnect());
if (code != CURLE_OK) {
return false;
}
return true;
}
//Process Get Request
int processGetTask(CCHttpRequest *request, write_callback callback, void *stream, int *responseCode)
{
CURLcode code = CURL_LAST;
CURL *curl = curl_easy_init();
do {
if (!configureCURL(curl))
{
break;
}
code = curl_easy_setopt(curl, CURLOPT_URL, request->getUrl());
if (code != CURLE_OK)
{
break;
}
code = curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, callback);
if (code != CURLE_OK)
{
break;
}
code = curl_easy_setopt(curl, CURLOPT_WRITEDATA, stream);
if (code != CURLE_OK)
{
break;
}
code = curl_easy_perform(curl);
if (code != CURLE_OK)
{
break;
}
code = curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, responseCode);
if (code != CURLE_OK || *responseCode != 200)
{
code = CURLE_HTTP_RETURNED_ERROR;
}
} while (0);
if (curl) {
curl_easy_cleanup(curl);
}
return (code == CURLE_OK ? 0 : 1);
}
//Process POST Request
int processPostTask(CCHttpRequest *request, write_callback callback, void *stream, int32_t *responseCode)
{
CURLcode code = CURL_LAST;
CURL *curl = curl_easy_init();
do {
if (!configureCURL(curl)) {
break;
}
code = curl_easy_setopt(curl, CURLOPT_URL, request->getUrl());
if (code != CURLE_OK) {
break;
}
code = curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, callback);
if (code != CURLE_OK) {
break;
}
code = curl_easy_setopt(curl, CURLOPT_WRITEDATA, stream);
if (code != CURLE_OK) {
break;
}
code = curl_easy_setopt(curl, CURLOPT_POST, 1);
if (code != CURLE_OK) {
break;
}
code = curl_easy_setopt(curl, CURLOPT_POSTFIELDS, request->getRequestData());
if (code != CURLE_OK) {
break;
}
code = curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, request->getRequestDataSize());
if (code != CURLE_OK) {
break;
}
code = curl_easy_perform(curl);
if (code != CURLE_OK) {
break;
}
code = curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, responseCode);
if (code != CURLE_OK || *responseCode != 200) {
code = CURLE_HTTP_RETURNED_ERROR;
}
} while (0);
if (curl) {
curl_easy_cleanup(curl);
}
return (code == CURLE_OK ? 0 : 1);
}
// HttpClient implementation
CCHttpClient* CCHttpClient::getInstance()
{
if (s_pHttpClient == NULL) {
s_pHttpClient = new CCHttpClient();
}
return s_pHttpClient;
}
void CCHttpClient::destroyInstance()
{
CCDirector::sharedDirector()->getScheduler()->unscheduleSelector(schedule_selector(CCHttpClient::dispatchResponseCallbacks),
CCHttpClient::getInstance());
CC_SAFE_RELEASE_NULL(s_pHttpClient);
}
CCHttpClient::CCHttpClient()
:_timeoutForRead(60)
,_timeoutForConnect(30)
{
CCDirector::sharedDirector()->getScheduler()->scheduleSelector(
schedule_selector(CCHttpClient::dispatchResponseCallbacks), this, 0, false);
CCDirector::sharedDirector()->getScheduler()->pauseTarget(this);
}
CCHttpClient::~CCHttpClient()
{
need_quit = true;
if (s_pSem != NULL) {
sem_post(s_pSem);
}
CCDirector::sharedDirector()->getScheduler()->unscheduleSelector(schedule_selector(CCHttpClient::dispatchResponseCallbacks), this);
}
//Lazy create semaphore & mutex & thread
bool CCHttpClient::lazyInitThreadSemphore()
{
if (s_pSem != NULL) {
return true;
} else {
#if CC_ASYNC_HTTPREQUEST_USE_NAMED_SEMAPHORE
s_pSem = sem_open(CC_ASYNC_HTTPREQUEST_SEMAPHORE, O_CREAT, 0644, 0);
if (s_pSem == SEM_FAILED) {
CCLog("Open HttpRequest Semaphore failed");
s_pSem = NULL;
return false;
}
#else
int semRet = sem_init(&s_sem, 0, 0);
if (semRet < 0) {
CCLog("Init HttpRequest Semaphore failed");
return false;
}
s_pSem = &s_sem;
#endif
s_requestQueue = new CCArray();
s_requestQueue->init();
s_responseQueue = new CCArray();
s_responseQueue->init();
pthread_mutex_init(&s_requestQueueMutex, NULL);
pthread_mutex_init(&s_responseQueueMutex, NULL);
pthread_create(&s_networkThread, NULL, networkThread, NULL);
pthread_detach(s_networkThread);
need_quit = false;
}
return true;
}
//Add a get task to queue
void CCHttpClient::send(CCHttpRequest* request)
{
if (false == lazyInitThreadSemphore())
{
return;
}
if (!request)
{
return;
}
++s_asyncRequestCount;
request->retain();
pthread_mutex_lock(&s_requestQueueMutex);
s_requestQueue->addObject(request);
pthread_mutex_unlock(&s_requestQueueMutex);
// Notify thread start to work
sem_post(s_pSem);
}
// Poll and notify main thread if responses exists in queue
void CCHttpClient::dispatchResponseCallbacks(float delta)
{
// CCLog("CCHttpClient::dispatchResponseCallbacks is running");
CCHttpResponse* response = NULL;
pthread_mutex_lock(&s_responseQueueMutex);
if (s_responseQueue->count())
{
response = dynamic_cast<CCHttpResponse*>(s_responseQueue->objectAtIndex(0));
s_responseQueue->removeObjectAtIndex(0);
}
pthread_mutex_unlock(&s_responseQueueMutex);
if (response)
{
--s_asyncRequestCount;
CCHttpRequest *request = response->getHttpRequest();
CCObject *pTarget = request->getTarget();
SEL_CallFuncND pSelector = request->getSelector();
if (pTarget && pSelector)
{
(pTarget->*pSelector)((CCNode *)this, response);
}
response->release();
}
if (0 == s_asyncRequestCount)
{
CCDirector::sharedDirector()->getScheduler()->pauseTarget(this);
}
}
NS_CC_EXT_END

View File

@ -0,0 +1,117 @@
/****************************************************************************
Copyright (c) 2010-2012 cocos2d-x.org
Copyright (c) 2012 greathqy
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
#ifndef __CCHTTPREQUEST_H__
#define __CCHTTPREQUEST_H__
#include "cocos2d.h"
#include "ExtensionMacros.h"
#include "HttpRequest.h"
#include "HttpResponse.h"
NS_CC_EXT_BEGIN
/**
* @addtogroup Network
* @{
*/
/** @brief Singleton that handles asynchrounous http requests
* Once the request completed, a callback will issued in main thread when it provided during make request
*/
class CCHttpClient : public cocos2d::CCObject
{
public:
/** Return the shared instance **/
static CCHttpClient *getInstance();
/** Relase the shared instance **/
static void destroyInstance();
/**
* Add a get request to task queue
* @param request a CCHttpRequest object, which includes url, response callback etc.
* @return NULL
*/
void send(CCHttpRequest* request);
/**
* Change the connect timeout
* @param timeout
* @return NULL
*/
inline void setTimeoutForConnect(int value) {_timeoutForConnect = value;};
/**
* Get connect timeout
* @return int
*
*/
inline int getTimeoutForConnect() {return _timeoutForConnect;}
/**
* Change the download timeout
* @param timeout
* @return NULL
*/
inline void setTimeoutForRead(int value) {_timeoutForRead = value;};
/**
* Get download timeout
* @return int
*/
inline int getTimeoutForRead() {return _timeoutForRead;};
private:
CCHttpClient();
virtual ~CCHttpClient();
bool init(void);
/**
* Init pthread mutex, semaphore, and create new thread for http requests
* @return bool
*/
bool lazyInitThreadSemphore();
/** Poll function called from main thread to dispatch callbacks when http requests finished **/
void dispatchResponseCallbacks(float delta);
private:
int _timeoutForConnect;
int _timeoutForRead;
// std::string reqId;
};
// end of Network group
/// @}
NS_CC_EXT_END
#endif //__CCHTTPREQUEST_H__

View File

@ -0,0 +1,192 @@
/****************************************************************************
Copyright (c) 2010-2012 cocos2d-x.org
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
#ifndef __HTTP_REQUEST_H__
#define __HTTP_REQUEST_H__
#include "cocos2d.h"
#include "ExtensionMacros.h"
NS_CC_EXT_BEGIN
/**
@brief defines the object which users must packed for CCHttpClient::send(HttpRequest*) method.
Please refer to samples/TestCpp/Classes/ExtensionTest/NetworkTest/HttpClientTest.cpp as a sample
@since v2.0.2
*/
class CCHttpRequest : public cocos2d::CCObject
{
public:
/** Use this enum type as param in setReqeustType(param) */
typedef enum
{
kHttpGet,
kHttpPost,
kHttpUnkown,
} HttpRequestType;
/** Constructor
Because HttpRequest object will be used between UI thead and network thread,
requestObj->autorelease() is forbidden to avoid crashes in CCAutoreleasePool
new/retain/release still works, which means you need to release it manually
Please refer to HttpRequestTest.cpp to find its usage
*/
CCHttpRequest()
{
_requestType = kHttpUnkown;
_url.clear();
_requestData.clear();
_tag.clear();
_pTarget = NULL;
_pSelector = NULL;
_pUserData = NULL;
};
/** Destructor */
virtual ~CCHttpRequest()
{
if (_pTarget)
{
_pTarget->release();
}
};
/** Override autorelease method to avoid developers to call it */
CCObject* autorelease(void)
{
CCAssert(false, "HttpResponse is used between network thread and ui thread \
therefore, autorelease is forbidden here");
return NULL;
}
// setter/getters for properties
/** Required field for HttpRequest object before being sent.
kHttpGet & kHttpPost is currently supported
*/
inline void setRequestType(HttpRequestType type)
{
_requestType = type;
};
/** Get back the kHttpGet/Post/... enum value */
inline HttpRequestType getRequestType()
{
return _requestType;
};
/** Required field for HttpRequest object before being sent.
*/
inline void setUrl(const char* url)
{
_url = url;
};
/** Get back the setted url */
inline const char* getUrl()
{
return _url.c_str();
};
/** Option field. You can set your post data here
*/
inline void setRequestData(const char* buffer, unsigned int len)
{
_requestData.assign(buffer, buffer + len);
};
/** Get the request data pointer back */
inline char* getRequestData()
{
return &(_requestData.front());
}
/** Get the size of request data back */
inline int getRequestDataSize()
{
return _requestData.size();
}
/** Option field. You can set a string tag to identify your request, this tag can be found in HttpResponse->getHttpRequest->getTag()
*/
inline void setTag(const char* tag)
{
_tag = tag;
};
/** Get the string tag back to identify the request.
The best practice is to use it in your MyClass::onMyHttpRequestCompleted(sender, HttpResponse*) callback
*/
inline const char* getTag()
{
return _tag.c_str();
};
/** Option field. You can attach a customed data in each request, and get it back in response callback.
But you need to new/delete the data pointer manully
*/
inline void setUserData(void* pUserData)
{
_pUserData = pUserData;
};
/** Get the pre-setted custom data pointer back.
Don't forget to delete it. HttpClient/HttpResponse/HttpRequest will do nothing with this pointer
*/
inline void* getUserData()
{
return _pUserData;
};
/** Required field. You should set the callback selector function at ack the http request completed
*/
inline void setResponseCallback(cocos2d::CCObject* pTarget, cocos2d::SEL_CallFuncND pSelector)
{
_pTarget = pTarget;
_pSelector = pSelector;
if (_pTarget)
{
_pTarget->retain();
}
}
/** Get the target of callback selector funtion, mainly used by CCHttpClient */
inline CCObject* getTarget()
{
return _pTarget;
}
/** Get the selector function pointer, mainly used by CCHttpClient */
inline cocos2d::SEL_CallFuncND getSelector()
{
return _pSelector;
}
protected:
// properties
HttpRequestType _requestType; /// kHttpRequestGet, kHttpRequestPost or other enums
std::string _url; /// target url that this request is sent to
std::vector<char> _requestData; /// used for POST
std::string _tag; /// user defined tag, to identify different requests in response callback
cocos2d::CCObject* _pTarget; /// callback target of pSelector function
cocos2d::SEL_CallFuncND _pSelector; /// callback function, e.g. MyLayer::onHttpResponse(CCObject *sender, void *data)
void* _pUserData; /// You can add your customed data here
};
NS_CC_EXT_END
#endif //__HTTP_REQUEST_H__

View File

@ -0,0 +1,169 @@
/****************************************************************************
Copyright (c) 2010-2012 cocos2d-x.org
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
#ifndef __HTTP_RESPONSE__
#define __HTTP_RESPONSE__
#include "cocos2d.h"
#include "ExtensionMacros.h"
#include "HttpRequest.h"
NS_CC_EXT_BEGIN
/**
@brief defines the object which users will receive at onHttpCompleted(sender, HttpResponse) callback
Please refer to samples/TestCpp/Classes/ExtensionTest/NetworkTest/HttpClientTest.cpp as a sample
@since v2.0.2
*/
class CCHttpResponse : public cocos2d::CCObject
{
public:
/** Constructor, it's used by CCHttpClient internal, users don't need to create HttpResponse manually
@param request the corresponding HttpRequest which leads to this response
*/
CCHttpResponse(CCHttpRequest* request)
{
_pHttpRequest = request;
if (_pHttpRequest)
{
_pHttpRequest->retain();
}
_succeed = false;
_responseData.clear();
_errorBuffer.clear();
}
/** Destructor, it will be called in CCHttpClient internal,
users don't need to desturct HttpResponse object manully
*/
virtual ~CCHttpResponse()
{
if (_pHttpRequest)
{
_pHttpRequest->release();
}
}
/** Override autorelease method to prevent developers from calling it */
CCObject* autorelease(void)
{
CCAssert(false, "HttpResponse is used between network thread and ui thread \
therefore, autorelease is forbidden here");
return NULL;
}
// getters, will be called by users
/** Get the corresponding HttpRequest object which leads to this response
There's no paired setter for it, coz it's already setted in class constructor
*/
inline CCHttpRequest* getHttpRequest()
{
return _pHttpRequest;
}
/** To see if the http reqeust is returned successfully,
Althrough users can judge if (http return code = 200), we want an easier way
If this getter returns false, you can call getResponseCode and getErrorBuffer to find more details
*/
inline bool isSucceed()
{
return _succeed;
};
/** Get the http response raw data */
inline std::vector<char>* getResponseData()
{
return &_responseData;
}
/** Get the http response errorCode
* I know that you want to see http 200 :)
*/
inline int getResponseCode()
{
return _responseCode;
}
/** Get the rror buffer which will tell you more about the reason why http request failed
*/
inline const char* getErrorBuffer()
{
return _errorBuffer.c_str();
}
// setters, will be called by CCHttpClient
// users should avoid invoking these methods
/** Set if the http request is returned successfully,
Althrough users can judge if (http code == 200), we want a easier way
This setter is mainly used in CCHttpClient, users mustn't set it directly
*/
inline void setSucceed(bool value)
{
_succeed = value;
};
/** Set the http response raw buffer, is used by CCHttpClient
*/
inline void setResponseData(std::vector<char>* data)
{
_responseData = *data;
}
/** Set the http response errorCode
*/
inline void setResponseCode(int value)
{
_responseCode = value;
}
/** Set the error buffer which will tell you more the reason why http request failed
*/
inline void setErrorBuffer(const char* value)
{
_errorBuffer.clear();
_errorBuffer.assign(value);
};
protected:
bool initWithRequest(CCHttpRequest* request);
// properties
CCHttpRequest* _pHttpRequest; /// the corresponding HttpRequest pointer who leads to this response
bool _succeed; /// to indecate if the http reqeust is successful simply
std::vector<char> _responseData; /// the returned raw data. You can also dump it as a string
int _responseCode; /// the status code returned from libcurl, e.g. 200, 404
std::string _errorBuffer; /// if _responseCode != 200, please read _errorBuffer to find the reason
};
NS_CC_EXT_END
#endif //__HTTP_RESPONSE_H__

View File

@ -41,7 +41,7 @@
<Tool
Name="VCCLCompilerTool"
Optimization="0"
AdditionalIncludeDirectories="&quot;$(SolutionDir)cocos2dx&quot;;&quot;$(SolutionDir)cocos2dx\include&quot;;&quot;$(SolutionDir)cocos2dx\kazmath\include&quot;;&quot;$(SolutionDir)cocos2dx\platform\win32&quot;;&quot;$(SolutionDir)cocos2dx\platform\third_party\win32\OGLES&quot;;..\"
AdditionalIncludeDirectories="&quot;$(SolutionDir)cocos2dx&quot;;&quot;$(SolutionDir)cocos2dx\include&quot;;&quot;$(SolutionDir)cocos2dx\kazmath\include&quot;;&quot;$(SolutionDir)cocos2dx\platform\win32&quot;;&quot;$(SolutionDir)cocos2dx\platform\third_party\win32&quot;;&quot;$(SolutionDir)cocos2dx\platform\third_party\win32\OGLES&quot;;&quot;$(SolutionDir)cocos2dx\platform\third_party\win32\pthread&quot;;..\"
PreprocessorDefinitions="WIN32;_WINDOWS;_DEBUG;_LIB;COCOS2D_DEBUG=1;_CRT_SECURE_NO_WARNINGS;_SCL_SECURE_NO_WARNINGS"
MinimalRebuild="true"
BasicRuntimeChecks="3"
@ -106,7 +106,7 @@
Name="VCCLCompilerTool"
Optimization="2"
EnableIntrinsicFunctions="true"
AdditionalIncludeDirectories="&quot;$(SolutionDir)cocos2dx&quot;;&quot;$(SolutionDir)cocos2dx\include&quot;;&quot;$(SolutionDir)cocos2dx\kazmath\include&quot;;&quot;$(SolutionDir)cocos2dx\platform\win32&quot;;&quot;$(SolutionDir)cocos2dx\platform\third_party\win32\OGLES&quot;;..\"
AdditionalIncludeDirectories="&quot;$(SolutionDir)cocos2dx&quot;;&quot;$(SolutionDir)cocos2dx\include&quot;;&quot;$(SolutionDir)cocos2dx\kazmath\include&quot;;&quot;$(SolutionDir)cocos2dx\platform\win32&quot;;&quot;$(SolutionDir)cocos2dx\platform\third_party\win32&quot;;&quot;$(SolutionDir)cocos2dx\platform\third_party\win32\OGLES&quot;;&quot;$(SolutionDir)cocos2dx\platform\third_party\win32\pthread&quot;;..\"
PreprocessorDefinitions="WIN32;_WINDOWS;NDEBUG;_LIB;_CRT_SECURE_NO_WARNINGS;_SCL_SECURE_NO_WARNINGS"
RuntimeLibrary="2"
EnableFunctionLevelLinking="true"
@ -423,6 +423,26 @@
</File>
</Filter>
</Filter>
<Filter
Name="network"
>
<File
RelativePath="..\network\HttpClient.cpp"
>
</File>
<File
RelativePath="..\network\HttpClient.h"
>
</File>
<File
RelativePath="..\network\HttpRequest.h"
>
</File>
<File
RelativePath="..\network\HttpResponse.h"
>
</File>
</Filter>
<File
RelativePath="..\cocos-ext.h"
>

View File

@ -1,4 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="Debug|Win32">
@ -51,7 +51,7 @@
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<ClCompile>
<Optimization>Disabled</Optimization>
<AdditionalIncludeDirectories>$(SolutionDir)cocos2dx;$(SolutionDir)cocos2dx\include;$(SolutionDir)cocos2dx\kazmath\include;$(SolutionDir)cocos2dx\platform\win32;$(SolutionDir)cocos2dx\platform\third_party\win32\OGLES;..\;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<AdditionalIncludeDirectories>$(SolutionDir)cocos2dx;$(SolutionDir)cocos2dx\include;$(SolutionDir)cocos2dx\kazmath\include;$(SolutionDir)cocos2dx\platform\win32;$(SolutionDir)cocos2dx\platform\third_party\win32;$(SolutionDir)cocos2dx\platform\third_party\win32\pthread;$(SolutionDir)cocos2dx\platform\third_party\win32\OGLES;..\;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<PreprocessorDefinitions>WIN32;_WINDOWS;_DEBUG;_LIB;COCOS2D_DEBUG=1;_CRT_SECURE_NO_WARNINGS;_SCL_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<MinimalRebuild>true</MinimalRebuild>
<BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
@ -67,7 +67,7 @@
<ClCompile>
<Optimization>MaxSpeed</Optimization>
<IntrinsicFunctions>true</IntrinsicFunctions>
<AdditionalIncludeDirectories>$(SolutionDir)cocos2dx;$(SolutionDir)cocos2dx\include;$(SolutionDir)cocos2dx\kazmath\include;$(SolutionDir)cocos2dx\platform\win32;$(SolutionDir)cocos2dx\platform\third_party\win32\OGLES;..\;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<AdditionalIncludeDirectories>$(SolutionDir)cocos2dx;$(SolutionDir)cocos2dx\include;$(SolutionDir)cocos2dx\kazmath\include;$(SolutionDir)cocos2dx\platform\win32;$(SolutionDir)cocos2dx\platform\third_party\win32;$(SolutionDir)cocos2dx\platform\third_party\win32\pthread;$(SolutionDir)cocos2dx\platform\third_party\win32\OGLES;..\;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<PreprocessorDefinitions>WIN32;_WINDOWS;NDEBUG;_LIB;_CRT_SECURE_NO_WARNINGS;_SCL_SECURE_NO_WARNINGS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<RuntimeLibrary>MultiThreadedDLL</RuntimeLibrary>
<FunctionLevelLinking>true</FunctionLevelLinking>
@ -109,6 +109,7 @@
<ClCompile Include="..\GUI\CCControlExtension\CCScale9Sprite.cpp" />
<ClCompile Include="..\GUI\CCControlExtension\CCSpacer.cpp" />
<ClCompile Include="..\GUI\CCScrollView\CCScrollView.cpp" />
<ClCompile Include="..\network\HttpClient.cpp" />
</ItemGroup>
<ItemGroup>
<ClInclude Include="..\CCBReader\CCBFileLoader.h" />
@ -148,6 +149,9 @@
<ClInclude Include="..\GUI\CCScrollView\CCScrollView.h" />
<ClInclude Include="..\cocos-ext.h" />
<ClInclude Include="..\ExtensionMacros.h" />
<ClInclude Include="..\network\HttpClient.h" />
<ClInclude Include="..\network\HttpRequest.h" />
<ClInclude Include="..\network\HttpResponse.h" />
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">

View File

@ -1,18 +1,21 @@
<?xml version="1.0" encoding="utf-8"?>
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup>
<Filter Include="CCBReader">
<UniqueIdentifier>{d37545ef-285b-4315-9fca-40da6fc2a6c9}</UniqueIdentifier>
</Filter>
<Filter Include="UI">
<Filter Include="GUI">
<UniqueIdentifier>{202b519b-b5e0-499f-b3b8-ed5da144b248}</UniqueIdentifier>
</Filter>
<Filter Include="UI\CCControlExtension">
<Filter Include="GUI\CCControlExtension">
<UniqueIdentifier>{c07abd14-e9dd-4e2d-85c4-a180070161b4}</UniqueIdentifier>
</Filter>
<Filter Include="UI\CCScrollView">
<Filter Include="GUI\CCScrollView">
<UniqueIdentifier>{46797895-f71d-4ddb-b381-d0884e678d39}</UniqueIdentifier>
</Filter>
<Filter Include="GUI\network">
<UniqueIdentifier>{2a7741ff-87a5-41c8-8e51-d7a1cf0c8e4d}</UniqueIdentifier>
</Filter>
</ItemGroup>
<ItemGroup>
<ClCompile Include="..\CCBReader\CCBFileLoader.cpp">
@ -67,43 +70,46 @@
<Filter>CCBReader</Filter>
</ClCompile>
<ClCompile Include="..\GUI\CCControlExtension\CCControl.cpp">
<Filter>UI\CCControlExtension</Filter>
<Filter>GUI\CCControlExtension</Filter>
</ClCompile>
<ClCompile Include="..\GUI\CCControlExtension\CCControlButton.cpp">
<Filter>UI\CCControlExtension</Filter>
<Filter>GUI\CCControlExtension</Filter>
</ClCompile>
<ClCompile Include="..\GUI\CCControlExtension\CCControlColourPicker.cpp">
<Filter>UI\CCControlExtension</Filter>
<Filter>GUI\CCControlExtension</Filter>
</ClCompile>
<ClCompile Include="..\GUI\CCControlExtension\CCControlHuePicker.cpp">
<Filter>UI\CCControlExtension</Filter>
<Filter>GUI\CCControlExtension</Filter>
</ClCompile>
<ClCompile Include="..\GUI\CCControlExtension\CCControlSaturationBrightnessPicker.cpp">
<Filter>UI\CCControlExtension</Filter>
<Filter>GUI\CCControlExtension</Filter>
</ClCompile>
<ClCompile Include="..\GUI\CCControlExtension\CCControlSlider.cpp">
<Filter>UI\CCControlExtension</Filter>
<Filter>GUI\CCControlExtension</Filter>
</ClCompile>
<ClCompile Include="..\GUI\CCControlExtension\CCControlSwitch.cpp">
<Filter>UI\CCControlExtension</Filter>
<Filter>GUI\CCControlExtension</Filter>
</ClCompile>
<ClCompile Include="..\GUI\CCControlExtension\CCControlUtils.cpp">
<Filter>UI\CCControlExtension</Filter>
<Filter>GUI\CCControlExtension</Filter>
</ClCompile>
<ClCompile Include="..\GUI\CCControlExtension\CCInvocation.cpp">
<Filter>UI\CCControlExtension</Filter>
<Filter>GUI\CCControlExtension</Filter>
</ClCompile>
<ClCompile Include="..\GUI\CCControlExtension\CCMenuPassive.cpp">
<Filter>UI\CCControlExtension</Filter>
<Filter>GUI\CCControlExtension</Filter>
</ClCompile>
<ClCompile Include="..\GUI\CCControlExtension\CCScale9Sprite.cpp">
<Filter>UI\CCControlExtension</Filter>
<Filter>GUI\CCControlExtension</Filter>
</ClCompile>
<ClCompile Include="..\GUI\CCControlExtension\CCSpacer.cpp">
<Filter>UI\CCControlExtension</Filter>
<Filter>GUI\CCControlExtension</Filter>
</ClCompile>
<ClCompile Include="..\GUI\CCScrollView\CCScrollView.cpp">
<Filter>UI\CCScrollView</Filter>
<Filter>GUI\CCScrollView</Filter>
</ClCompile>
<ClCompile Include="..\network\HttpClient.cpp">
<Filter>GUI\network</Filter>
</ClCompile>
</ItemGroup>
<ItemGroup>
@ -171,48 +177,57 @@
<Filter>CCBReader</Filter>
</ClInclude>
<ClInclude Include="..\GUI\CCControlExtension\CCControl.h">
<Filter>UI\CCControlExtension</Filter>
<Filter>GUI\CCControlExtension</Filter>
</ClInclude>
<ClInclude Include="..\GUI\CCControlExtension\CCControlButton.h">
<Filter>UI\CCControlExtension</Filter>
<Filter>GUI\CCControlExtension</Filter>
</ClInclude>
<ClInclude Include="..\GUI\CCControlExtension\CCControlColourPicker.h">
<Filter>UI\CCControlExtension</Filter>
<Filter>GUI\CCControlExtension</Filter>
</ClInclude>
<ClInclude Include="..\GUI\CCControlExtension\CCControlExtensions.h">
<Filter>UI\CCControlExtension</Filter>
<Filter>GUI\CCControlExtension</Filter>
</ClInclude>
<ClInclude Include="..\GUI\CCControlExtension\CCControlHuePicker.h">
<Filter>UI\CCControlExtension</Filter>
<Filter>GUI\CCControlExtension</Filter>
</ClInclude>
<ClInclude Include="..\GUI\CCControlExtension\CCControlSaturationBrightnessPicker.h">
<Filter>UI\CCControlExtension</Filter>
<Filter>GUI\CCControlExtension</Filter>
</ClInclude>
<ClInclude Include="..\GUI\CCControlExtension\CCControlSlider.h">
<Filter>UI\CCControlExtension</Filter>
<Filter>GUI\CCControlExtension</Filter>
</ClInclude>
<ClInclude Include="..\GUI\CCControlExtension\CCControlSwitch.h">
<Filter>UI\CCControlExtension</Filter>
<Filter>GUI\CCControlExtension</Filter>
</ClInclude>
<ClInclude Include="..\GUI\CCControlExtension\CCControlUtils.h">
<Filter>UI\CCControlExtension</Filter>
<Filter>GUI\CCControlExtension</Filter>
</ClInclude>
<ClInclude Include="..\GUI\CCControlExtension\CCInvocation.h">
<Filter>UI\CCControlExtension</Filter>
<Filter>GUI\CCControlExtension</Filter>
</ClInclude>
<ClInclude Include="..\GUI\CCControlExtension\CCMenuPassive.h">
<Filter>UI\CCControlExtension</Filter>
<Filter>GUI\CCControlExtension</Filter>
</ClInclude>
<ClInclude Include="..\GUI\CCControlExtension\CCScale9Sprite.h">
<Filter>UI\CCControlExtension</Filter>
<Filter>GUI\CCControlExtension</Filter>
</ClInclude>
<ClInclude Include="..\GUI\CCControlExtension\CCSpacer.h">
<Filter>UI\CCControlExtension</Filter>
<Filter>GUI\CCControlExtension</Filter>
</ClInclude>
<ClInclude Include="..\GUI\CCScrollView\CCScrollView.h">
<Filter>UI\CCScrollView</Filter>
<Filter>GUI\CCScrollView</Filter>
</ClInclude>
<ClInclude Include="..\cocos-ext.h" />
<ClInclude Include="..\ExtensionMacros.h" />
<ClInclude Include="..\network\HttpClient.h">
<Filter>GUI\network</Filter>
</ClInclude>
<ClInclude Include="..\network\HttpRequest.h">
<Filter>GUI\network</Filter>
</ClInclude>
<ClInclude Include="..\network\HttpResponse.h">
<Filter>GUI\network</Filter>
</ClInclude>
</ItemGroup>
</Project>

View File

@ -49,6 +49,7 @@ Classes/ExtensionsTest/CocosBuilderTest/HelloCocosBuilder/HelloCocosBuilderLayer
Classes/ExtensionsTest/CocosBuilderTest/TestHeader/TestHeaderLayer.cpp \
Classes/ExtensionsTest/CocosBuilderTest/ButtonTest/ButtonTestLayer.cpp \
Classes/ExtensionsTest/CocosBuilderTest/MenuTest/MenuTestLayer.cpp \
Classes/ExtensionsTest/NetworkTest/HttpClientTest.cpp \
Classes/FontTest/FontTest.cpp \
Classes/IntervalTest/IntervalTest.cpp \
Classes/KeypadTest/KeypadTest.cpp \
@ -86,8 +87,6 @@ Classes/controller.cpp \
Classes/testBasic.cpp \
Classes/AppDelegate.cpp
LOCAL_STATIC_LIBRARIES := curl_static_prebuilt
LOCAL_WHOLE_STATIC_LIBRARIES := cocos2dx_static
LOCAL_WHOLE_STATIC_LIBRARIES += cocosdenshion_static
LOCAL_WHOLE_STATIC_LIBRARIES += box2d_static
@ -102,5 +101,4 @@ $(call import-module,CocosDenshion/android)
$(call import-module,external/Box2D)
$(call import-module,external/chipmunk)
$(call import-module,cocos2dx)
$(call import-module,cocos2dx/platform/third_party/android/prebuilt/libcurl)
$(call import-module,extensions)

View File

@ -3,6 +3,7 @@
#include "NotificationCenterTest/NotificationCenterTest.h"
#include "ControlExtensionTest/CCControlSceneManager.h"
#include "CocosBuilderTest/CocosBuilderTest.h"
#include "NetworkTest/HttpClientTest.h"
enum
{
@ -15,6 +16,7 @@ enum
TEST_NOTIFICATIONCENTER = 0,
TEST_CCCONTROLBUTTON,
TEST_COCOSBUILDER,
TEST_HTTPCLIENT,
TEST_MAX_COUNT,
};
@ -23,6 +25,7 @@ static const std::string testsName[TEST_MAX_COUNT] =
"NotificationCenterTest",
"CCControlButtonTest",
"CocosBuilderTest",
"HttpClientTest",
};
////////////////////////////////////////////////////////
@ -80,6 +83,10 @@ void ExtensionsMainLayer::menuCallback(CCObject* pSender)
}
}
break;
case TEST_HTTPCLIENT:
{
runHttpClientTest();
}
default:
break;
}

View File

@ -0,0 +1,194 @@
#include "HttpClientTest.h"
#include "../ExtensionsTest.h"
#include <string>
USING_NS_CC;
USING_NS_CC_EXT;
HttpClientTest::HttpClientTest()
: m_labelStatusCode(NULL)
{
CCSize winSize = CCDirector::sharedDirector()->getWinSize();
CCLabelTTF *label = CCLabelTTF::create("Http Request Test", "Arial", 28);
label->setPosition(ccp(winSize.width / 2, winSize.height - 50));
addChild(label, 0);
CCMenu *menuRequest = CCMenu::create();
menuRequest->setPosition(CCPointZero);
addChild(menuRequest);
// Get
CCLabelTTF *labelGet = CCLabelTTF::create("Test Get", "Arial", 22);
CCMenuItemLabel *itemGet = CCMenuItemLabel::create(labelGet, this, menu_selector(HttpClientTest::onMenuGetTestClicked));
itemGet->setPosition(ccp(winSize.width / 2, winSize.height - 100));
menuRequest->addChild(itemGet);
// Post
CCLabelTTF *labelPost = CCLabelTTF::create("Test Post", "Arial", 22);
CCMenuItemLabel *itemPost = CCMenuItemLabel::create(labelPost, this, menu_selector(HttpClientTest::onMenuPostTestClicked));
itemPost->setPosition(ccp(winSize.width / 2, winSize.height - 150));
menuRequest->addChild(itemPost);
// Post Binary
CCLabelTTF *labelPostBinary = CCLabelTTF::create("Test Post Binary", "Arial", 22);
CCMenuItemLabel *itemPostBinary = CCMenuItemLabel::create(labelPostBinary, this, menu_selector(HttpClientTest::onMenuPostBinaryTestClicked));
itemPostBinary->setPosition(ccp(winSize.width / 2, winSize.height - 200));
menuRequest->addChild(itemPostBinary);
// Response Code Label
m_labelStatusCode = CCLabelTTF::create("HTTP Status Code", "Marker Felt", 20);
m_labelStatusCode->setPosition(ccp(winSize.width / 2, winSize.height - 250));
addChild(m_labelStatusCode);
// Back Menu
CCMenuItemFont *itemBack = CCMenuItemFont::create("Back", this, menu_selector(HttpClientTest::toExtensionsMainLayer));
itemBack->setPosition(ccp(winSize.width - 50, 25));
CCMenu *menuBack = CCMenu::create(itemBack, NULL);
menuBack->setPosition(CCPointZero);
addChild(menuBack);
}
HttpClientTest::~HttpClientTest()
{
CCHttpClient::getInstance()->destroyInstance();
}
void HttpClientTest::onMenuGetTestClicked(cocos2d::CCObject *sender)
{
// test 1
{
CCHttpRequest* request = new CCHttpRequest();
request->setUrl("http://just-make-this-request-failed.com");
request->setRequestType(CCHttpRequest::kHttpGet);
request->setResponseCallback(this, callfuncND_selector(HttpClientTest::onHttpRequestCompleted));
request->setTag("GET test1");
CCHttpClient::getInstance()->send(request);
request->release();
}
// test 2
{
CCHttpRequest* request = new CCHttpRequest();
// required fields
request->setUrl("http://www.httpbin.org/ip");
request->setRequestType(CCHttpRequest::kHttpGet);
request->setResponseCallback(this, callfuncND_selector(HttpClientTest::onHttpRequestCompleted));
// optional fields
request->setTag("GET test2");
CCHttpClient::getInstance()->send(request);
// don't forget to release it, pair to new
request->release();
}
// test 3
{
CCHttpRequest* request = new CCHttpRequest();
request->setUrl("http://www.httpbin.org/get");
request->setRequestType(CCHttpRequest::kHttpGet);
request->setResponseCallback(this, callfuncND_selector(HttpClientTest::onHttpRequestCompleted));
request->setTag("GET test3");
CCHttpClient::getInstance()->send(request);
request->release();
}
// waiting
m_labelStatusCode->setString("waiting...");
}
void HttpClientTest::onMenuPostTestClicked(cocos2d::CCObject *sender)
{
CCHttpRequest* request = new CCHttpRequest();
request->setUrl("http://www.httpbin.org/post");
request->setRequestType(CCHttpRequest::kHttpPost);
request->setResponseCallback(this, callfuncND_selector(HttpClientTest::onHttpRequestCompleted));
// write the post data
const char* postData = "visitor=cocos2d&TestSuite=Extensions Test/NetowrkTest";
request->setRequestData(postData, strlen(postData));
request->setTag("POST test");
CCHttpClient::getInstance()->send(request);
request->release();
// waiting
m_labelStatusCode->setString("waiting...");
}
void HttpClientTest::onMenuPostBinaryTestClicked(cocos2d::CCObject *sender)
{
CCHttpRequest* request = new CCHttpRequest();
request->setUrl("http://www.httpbin.org/post");
request->setRequestType(CCHttpRequest::kHttpPost);
request->setResponseCallback(this, callfuncND_selector(HttpClientTest::onHttpRequestCompleted));
// write the post data
char postData[22] = "binary=hello\0\0cocos2d"; // including \0, the strings after \0 should not be cut in response
request->setRequestData(postData, 22);
request->setTag("POST Binary test");
CCHttpClient::getInstance()->send(request);
request->release();
// waiting
m_labelStatusCode->setString("waiting...");
}
void HttpClientTest::onHttpRequestCompleted(cocos2d::CCNode *sender, void *data)
{
CCHttpResponse *response = (CCHttpResponse*)data;
if (!response)
{
return;
}
// You can get original request type from: response->request->reqType
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());
m_labelStatusCode->setString(statusString);
CCLog("response code: %d", statusCode);
if (!response->isSucceed())
{
CCLog("response failed");
CCLog("error buffer: %s", response->getErrorBuffer());
return;
}
// dump data
std::vector<char> *buffer = response->getResponseData();
printf("Http Test, dump data: ");
for (int i = 0; i < buffer->size(); i++)
{
printf("%c", (*buffer)[i]);
}
printf("\n");
}
void HttpClientTest::toExtensionsMainLayer(cocos2d::CCObject *sender)
{
ExtensionsTestScene *pScene = new ExtensionsTestScene();
pScene->runThisTest();
pScene->release();
}
void runHttpClientTest()
{
CCScene *pScene = CCScene::create();
HttpClientTest *pLayer = new HttpClientTest();
pScene->addChild(pLayer);
CCDirector::sharedDirector()->replaceScene(pScene);
pLayer->release();
}

View File

@ -0,0 +1,28 @@
#ifndef __HTTP_CLIENT_H__
#define __HTTP_CLIENT_H__
#include "cocos2d.h"
#include "cocos-ext.h"
class HttpClientTest : public cocos2d::CCLayer
{
public:
HttpClientTest();
virtual ~HttpClientTest();
void toExtensionsMainLayer(cocos2d::CCObject *sender);
//Menu Callbacks
void onMenuGetTestClicked(cocos2d::CCObject *sender);
void onMenuPostTestClicked(cocos2d::CCObject *sender);
void onMenuPostBinaryTestClicked(cocos2d::CCObject *sender);
//Http Response Callback
void onHttpRequestCompleted(cocos2d::CCNode *sender, void *data);
private:
cocos2d::CCLabelTTF* m_labelStatusCode;
};
void runHttpClientTest();
#endif //__HTTPREQUESTHTTP_H

View File

@ -1 +1 @@
7dea09f758e229595c7992fee3cc0a0f0fb49f79
86f6b6c3837508de917c08ed3e087b901da16e27

View File

@ -21,6 +21,7 @@ INCLUDES = -I../ \
-I$(COCOS2DX_PATH)/platform/third_party/linux/glew-1.7.0/glew-1.7.0/include/ \
-I$(COCOS2DX_PATH)/platform/third_party/linux/libxml2 \
-I$(COCOS2DX_PATH)/platform/third_party/linux/libjpeg \
-I$(COCOS2DX_PATH)/platform/third_party/linux/curl \
-I../../../CocosDenshion/include \
-I../../../extensions/ \
-I../../../external/ \
@ -78,6 +79,7 @@ OBJECTS = ../Classes/AccelerometerTest/AccelerometerTest.o \
../Classes/ExtensionsTest/ControlExtensionTest/CCControlSwitchTest/CCControlSwitchTest.o \
../Classes/ExtensionsTest/ExtensionsTest.o \
../Classes/ExtensionsTest/NotificationCenterTest/NotificationCenterTest.o \
../Classes/ExtensionsTest/NetworkTest/HttpClientTest.o \
../Classes/FontTest/FontTest.o \
../Classes/IntervalTest/IntervalTest.o \
../Classes/KeypadTest/KeypadTest.o \

View File

@ -1 +1 @@
04e861a3cc213902d2d09aad426257c2e326b22c
30057061474e27b1b05c7ad738c37006a78bcba0

View File

@ -41,7 +41,7 @@
<Tool
Name="VCCLCompilerTool"
Optimization="0"
AdditionalIncludeDirectories="&quot;$(SolutionDir)cocos2dx&quot;;&quot;$(SolutionDir)cocos2dx\include&quot;;&quot;$(SolutionDir)cocos2dx\kazmath\include&quot;;&quot;$(SolutionDir)cocos2dx\platform\win32&quot;;&quot;$(SolutionDir)cocos2dx\platform\third_party\win32&quot;;&quot;$(SolutionDir)cocos2dx\platform\third_party\win32\OGLES&quot;;&quot;$(SolutionDir)external&quot;;&quot;$(SolutionDir)external\chipmunk\include\chipmunk&quot;;&quot;$(SolutionDir)CocosDenshion\include&quot;;&quot;$(SolutionDir)extensions&quot;;..\Classes;.."
AdditionalIncludeDirectories="&quot;$(SolutionDir)cocos2dx&quot;;&quot;$(SolutionDir)cocos2dx\include&quot;;&quot;$(SolutionDir)cocos2dx\kazmath\include&quot;;&quot;$(SolutionDir)cocos2dx\platform\win32&quot;;&quot;$(SolutionDir)cocos2dx\platform\third_party\win32&quot;;&quot;$(SolutionDir)cocos2dx\platform\third_party\win32\OGLES&quot;;&quot;$(SolutionDir)cocos2dx\platform\third_party\win32\pthread&quot;;&quot;$(SolutionDir)external&quot;;&quot;$(SolutionDir)external\chipmunk\include\chipmunk&quot;;&quot;$(SolutionDir)CocosDenshion\include&quot;;&quot;$(SolutionDir)extensions&quot;;..\Classes;.."
PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;_USE_MATH_DEFINES;GL_GLEXT_PROTOTYPES;COCOS2D_DEBUG=1;_CRT_SECURE_NO_WARNINGS;_SCL_SECURE_NO_WARNINGS"
MinimalRebuild="true"
BasicRuntimeChecks="3"
@ -62,7 +62,7 @@
/>
<Tool
Name="VCLinkerTool"
AdditionalDependencies="libExtensions.lib libcocos2d.lib libCocosDenshion.lib opengl32.lib glew32.lib libBox2d.lib libchipmunk.lib libcurl_imp.lib"
AdditionalDependencies="libExtensions.lib libcocos2d.lib libCocosDenshion.lib opengl32.lib glew32.lib libBox2d.lib libchipmunk.lib libcurl_imp.lib pthreadVCE2.lib"
OutputFile="$(OutDir)\$(ProjectName).exe"
LinkIncremental="2"
AdditionalLibraryDirectories="&quot;$(OutDir)&quot;"
@ -120,7 +120,7 @@
Name="VCCLCompilerTool"
Optimization="2"
EnableIntrinsicFunctions="true"
AdditionalIncludeDirectories="&quot;$(SolutionDir)cocos2dx&quot;;&quot;$(SolutionDir)cocos2dx\include&quot;;&quot;$(SolutionDir)cocos2dx\kazmath\include&quot;;&quot;$(SolutionDir)cocos2dx\platform\win32&quot;;&quot;$(SolutionDir)cocos2dx\platform\third_party\win32&quot;;&quot;$(SolutionDir)cocos2dx\platform\third_party\win32\OGLES&quot;;&quot;$(SolutionDir)external&quot;;&quot;$(SolutionDir)external\chipmunk\include\chipmunk&quot;;&quot;$(SolutionDir)CocosDenshion\include&quot;;&quot;$(SolutionDir)extensions&quot;;..\Classes;.."
AdditionalIncludeDirectories="&quot;$(SolutionDir)cocos2dx&quot;;&quot;$(SolutionDir)cocos2dx\include&quot;;&quot;$(SolutionDir)cocos2dx\kazmath\include&quot;;&quot;$(SolutionDir)cocos2dx\platform\win32&quot;;&quot;$(SolutionDir)cocos2dx\platform\third_party\win32&quot;;&quot;$(SolutionDir)cocos2dx\platform\third_party\win32\OGLES&quot;;&quot;$(SolutionDir)cocos2dx\platform\third_party\win32\pthread&quot;;&quot;$(SolutionDir)external&quot;;&quot;$(SolutionDir)external\chipmunk\include\chipmunk&quot;;&quot;$(SolutionDir)CocosDenshion\include&quot;;&quot;$(SolutionDir)extensions&quot;;..\Classes;.."
PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS;_USE_MATH_DEFINES;GL_GLEXT_PROTOTYPES;_CRT_SECURE_NO_WARNINGS;_SCL_SECURE_NO_WARNINGS"
RuntimeLibrary="2"
EnableFunctionLevelLinking="true"
@ -140,7 +140,7 @@
/>
<Tool
Name="VCLinkerTool"
AdditionalDependencies="libcocos2d.lib libCocosDenshion.lib opengl32.lib glew32.lib libBox2d.lib libchipmunk.lib libcurl_imp.lib libExtensions.lib"
AdditionalDependencies="libcocos2d.lib libCocosDenshion.lib opengl32.lib glew32.lib libBox2d.lib libchipmunk.lib libcurl_imp.lib libExtensions.lib pthreadVCE2.lib"
OutputFile="$(OutDir)\$(ProjectName).exe"
LinkIncremental="1"
AdditionalLibraryDirectories="&quot;$(OutDir)&quot;"
@ -1011,6 +1011,18 @@
</File>
</Filter>
</Filter>
<Filter
Name="NetworkTest"
>
<File
RelativePath="..\Classes\ExtensionsTest\NetworkTest\HttpClientTest.cpp"
>
</File>
<File
RelativePath="..\Classes\ExtensionsTest\NetworkTest\HttpClientTest.h"
>
</File>
</Filter>
</Filter>
<Filter
Name="NodeTest"

View File

@ -65,7 +65,7 @@
<DisableSpecificWarnings>4267;4251;4244;%(DisableSpecificWarnings)</DisableSpecificWarnings>
</ClCompile>
<Link>
<AdditionalDependencies>libExtensions.lib;libcocos2d.lib;libCocosDenshion.lib;opengl32.lib;glew32.lib;libBox2d.lib;libchipmunk.lib;libcurl_imp.lib;%(AdditionalDependencies)</AdditionalDependencies>
<AdditionalDependencies>libExtensions.lib;libcocos2d.lib;libCocosDenshion.lib;opengl32.lib;glew32.lib;libBox2d.lib;libchipmunk.lib;libcurl_imp.lib;pthreadVCE2.lib;%(AdditionalDependencies)</AdditionalDependencies>
<OutputFile>$(OutDir)$(ProjectName).exe</OutputFile>
<AdditionalLibraryDirectories>$(OutDir);%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
<GenerateDebugInformation>true</GenerateDebugInformation>
@ -92,7 +92,7 @@
<DisableSpecificWarnings>4267;4251;4244;%(DisableSpecificWarnings)</DisableSpecificWarnings>
</ClCompile>
<Link>
<AdditionalDependencies>libcocos2d.lib;libCocosDenshion.lib;opengl32.lib;glew32.lib;libBox2d.lib;libchipmunk.lib;libcurl_imp.lib;libExtensions.lib;%(AdditionalDependencies)</AdditionalDependencies>
<AdditionalDependencies>libcocos2d.lib;libCocosDenshion.lib;opengl32.lib;glew32.lib;libBox2d.lib;libchipmunk.lib;libcurl_imp.lib;libExtensions.lib;pthreadVCE2.lib;%(AdditionalDependencies)</AdditionalDependencies>
<OutputFile>$(OutDir)$(ProjectName).exe</OutputFile>
<AdditionalLibraryDirectories>$(OutDir);%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
<GenerateDebugInformation>true</GenerateDebugInformation>
@ -107,6 +107,7 @@
</PostBuildEvent>
</ItemDefinitionGroup>
<ItemGroup>
<ClCompile Include="..\Classes\ExtensionsTest\NetworkTest\HttpClientTest.cpp" />
<ClCompile Include="main.cpp" />
<ClCompile Include="..\Classes\AppDelegate.cpp" />
<ClCompile Include="..\Classes\controller.cpp" />
@ -188,6 +189,7 @@
<ClCompile Include="..\Classes\MutiTouchTest\MutiTouchTest.cpp" />
</ItemGroup>
<ItemGroup>
<ClInclude Include="..\Classes\ExtensionsTest\NetworkTest\HttpClientTest.h" />
<ClInclude Include="main.h" />
<ClInclude Include="..\Classes\AppDelegate.h" />
<ClInclude Include="..\Classes\controller.h" />

View File

@ -187,6 +187,9 @@
<Filter Include="Classes\MutiTouchTest">
<UniqueIdentifier>{b3be049f-74ff-44a5-8895-0766e4807671}</UniqueIdentifier>
</Filter>
<Filter Include="Classes\ExtensionsTest\NetworkTest">
<UniqueIdentifier>{28e8af6a-0e73-4069-bdf4-735138ed886d}</UniqueIdentifier>
</Filter>
</ItemGroup>
<ItemGroup>
<ClCompile Include="main.cpp">
@ -426,6 +429,9 @@
<ClCompile Include="..\Classes\MutiTouchTest\MutiTouchTest.cpp">
<Filter>Classes\MutiTouchTest</Filter>
</ClCompile>
<ClCompile Include="..\Classes\ExtensionsTest\NetworkTest\HttpClientTest.cpp">
<Filter>Classes\ExtensionsTest\NetworkTest</Filter>
</ClCompile>
</ItemGroup>
<ItemGroup>
<ClInclude Include="main.h">
@ -839,5 +845,8 @@
<ClInclude Include="..\Classes\MutiTouchTest\MutiTouchTest.h">
<Filter>Classes\MutiTouchTest</Filter>
</ClInclude>
<ClInclude Include="..\Classes\ExtensionsTest\NetworkTest\HttpClientTest.h">
<Filter>Classes\ExtensionsTest\NetworkTest</Filter>
</ClInclude>
</ItemGroup>
</Project>