Http.h//文件
// Http.h
// http
// 群 :202396239 手游前后端交谊群
// Created by 成少 on 15/8/23.
//
//
#ifndef _ChengShao__Http__
#define _ChengShao__Http__
#include <stdio.h>
#include "cocos2d.h"
#include "network/HttpClient.h"
USING_NS_CC;
using namespace network;
#define user_login "user_login" ---------------------------a
class Http
{
public:
~Http();
Http();
staticHttp* getInstance();
void send(constchar* param,std::string tagId); -----------------------------------b
void onHttpRequestCompleted(network::HttpClient *sender,network::HttpResponse *response);------------c
private:
staticHttp* m_http;
};
#endif /* defined(_Http__) */
Http.cpp 文件
//
// Http.cpp
// Http
//群 :202396239 手游前后端交谊群
// Created by 成少 on 15/8/23.
//
//
#include "Http.h"
Http* Http::m_http =nullptr;
Http::~Http()
{
CC_SAFE_DELETE(m_http);
}
Http::Http()
{
}
Http* Http::getInstance()
{
if (m_http ==nullptr) {
m_http =new Http();
}
returnm_http;
}
void Http::send(constchar* param,std::string tagId)
{
HttpRequest* request =new HttpRequest();
request->setRequestType(HttpRequest::Type::POST);
request->setUrl("localhost:8888");
request->setResponseCallback(CC_CALLBACK_2(Http::onHttpRequestCompleted,this));
request->setRequestData(param,strlen(param));//
// 添加post请求参数
/*
const char* postData = "{\
\"DeviceID\" : \"device id of the phone\"\
}";
request->setRequestData(postData, strlen(postData));//
*/
request->setTag(tagId.c_str());//
cocos2d::network::HttpClient::getInstance()->send(request);
request->release();
}
void Http::onHttpRequestCompleted(network::HttpClient *sender,network::HttpResponse *response)
{
if (!response) {
return;
}
if (0 !=strlen(response->getHttpRequest()->getTag()) ) {
log("%s completed",response->getHttpRequest()->getTag());
}
std::vector<char>* header = response->getResponseHeader();
for (unsigned int i = 0; i < header->size(); i++)
{
printf("%c", (*header)[i]);
}
printf("\n");
int statusCode = response->getResponseCode();
log("response code: %d", statusCode);
if (!response->isSucceed())
{
log("response failed");
log("error buffer: %s", response->getErrorBuffer());
return;
}
// 打印 response data
std::vector<char> *buffer = response->getResponseData();
for (unsigned int i = 0; i < buffer->size(); i++)
{
printf("%c", (*buffer)[i]);
}
printf("\n");
}
a 处定义一个宏,作为一个tag标记,和后端通信的一个标志,如用户登录
b 向后端发送信息
c 后端回调函数