我是cocos2dx中的新手..我对json解析有些疑惑。我收到了来自服务器的消息。但我无法将消息发布到服务器。在这里我粘贴getmessages的代码。 Plz帮我发帖子。谢谢你。
void ChatRoom::function()
{
std::vector<std::string> headers;
headers.push_back("Content-Type: application/json; charset=utf-8");
cocos2d::extension::CCHttpRequest * request = new cocos2d::extension::CCHttpRequest();
request->setUrl("url here");
const char* postData ="chatManagerRequestType=GET_MESSAGES_AFTER_CHAT_ENABLED";
request->setRequestType(cocos2d::extension::CCHttpRequest::kHttpGet);
request->setResponseCallback(this, httpresponse_selector(ChatRoom::onHttpRequestCompleted));
request->setRequestData(postData, strlen(postData));
request->setHeaders(headers);
cocos2d::extension::CCHttpClient::getInstance()->send(request);
request->release();
}
void ChatRoom::onHttpRequestCompleted(cocos2d::CCNode *sender, void *data)
{
cocos2d::extension::CCHttpResponse * response = (cocos2d::extension::CCHttpResponse *)data;
if (!response)
{
return;
} std::string command;
if (0 != strlen(response->getHttpRequest()->getTag()))
{
command = 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());
return;
}
std::vector<char> * buffer = response->getResponseData();
char * concatenated = (char *) malloc(buffer->size() + 1);
std::string s2(buffer->begin(), buffer->end());
strcpy(concatenated, s2.c_str());
CCLOG("%s",s2.c_str());
CCArray *arry=new CCArray();
printf("Http Test, dump data: ");
std::string tstr;
for (unsigned int i = 0; i < buffer->size(); i++)
{
char s[10];
sprintf(s, "%c",(*buffer)[i]);
tstr += (*buffer)[i];
arry->addObject((CCObject*)s);
}
for (int i=0; i<9; i++) {
cocos2d::extension::Json * jsondd = cocos2d::extension::Json_create(concatenated);
cocos2d::extension::Json *json1 = cocos2d::extension::Json_getItem(jsondd, "chatValueList");
cocos2d::extension::Json *json2 = cocos2d::extension::Json_getItemAt (json1, 0);
cocos2d::extension::Json *json3 = cocos2d::extension::Json_getItem(json2,"message");
cocos2d::extension::Json *json31 = cocos2d::extension::Json_getItem(json2,"chatId");
cocos2d::extension::Json *json4= cocos2d::extension::Json_getItem(json2,"userValue");
cocos2d::extension::Json *json5= cocos2d::extension::Json_getItem(json4,"userName");
cocos2d::extension::Json *json6= cocos2d::extension::Json_getItem(json4,"emailId");
val1 = json5->valuestring;
val2 = json3->valuestring;
val3 = json31->valueint;
CCLOG("value:%s %s %d",val1.getCString(),val2.getCString(),val3);
}
}
答案 0 :(得分:1)
首先,要使用http发布数据,你必须使用kHttpPost而不是kHttpGet。因此,如果您只是将请求类型设置为CCHttpRequest :: kHttpPost,您就可以将您的发布数据发送到服务器。
其次,如果你没有遇到json的麻烦,那么就不要在问题标题中提及它。它误导了用户。