とあるプログラマの備忘録

都内某所に住むプログラマが自分用に備忘録を残すという趣旨のブログです。はてなダイアリーから移動しました!

Cocos2dx Http通信で外部DBから取得した値をpicojsonで解析する

前回websocketでの通信を試してみたんですけど、
今回はHTTP通信でやってみます。

JSONパーサーはkazuhoさんが公開しているpicojsonを使用させていただきました。 /lang/cplusplus/picojson/trunk/picojson.h – CodeRepos::Share – Trac
他の人はspine/Json.h使っているのが普通なんでしょうか?

では早速

レスポンスデータは以下の状態としています。

{"id":1000101001,"title":"とあるプログラマの備忘録","is_bool":false}

HelloWorld.h

#ifndef __HELLOWORLD_SCENE_H__
#define __HELLOWORLD_SCENE_H__

#include "cocos2d.h"

#include <HttpRequest.h>
#include <HttpClient.h>


USING_NS_CC;
using namespace network;

class HelloWorld : public cocos2d::Layer
{
public:
    static cocos2d::Scene* createScene();
    virtual bool init();
    CREATE_FUNC(HelloWorld);
    
    //Callback
    void onHttpRequestCallBack(HttpClient* sender, HttpResponse* response);
    
};

#endif // __HELLOWORLD_SCENE_H__

ヘッダー読み込みとコールバックメソッドの宣言してるだけ

HelloWorld.cpp

#include "HelloWorldScene.h"
#include "picojson.h"

Scene* HelloWorld::createScene()
{
    auto scene = Scene::create();
    auto layer = HelloWorld::create();
    scene->addChild(layer);
    return scene;
}

// on "init" you need to initialize your instance
bool HelloWorld::init()
{
    if ( !Layer::init() ) return false;
    
    //HTTP通信
    std::vector<std::string> headers;
    headers.push_back("Content-Type: application/json; charset=utf-8");
    HttpRequest *request = new HttpRequest();
    
    request->setUrl("http://domain.net/*****");  //URLは自分の環境にあわせてください
    request->setRequestType(HttpRequest::Type::GET);
    auto ad = &HelloWorld::onHttpRequestCallBack;
    request->setResponseCallback(this, SEL_HttpResponse(ad));
    request->setHeaders(headers);
    HttpClient::getInstance()->send(request);
    request->release();
    
    return true;
}

//callback
void HelloWorld::onHttpRequestCallBack(HttpClient* sender, HttpResponse* response)
{
    picojson::value response_data;
    std::string err;
    
    CCASSERT(response, "response empty");
    CCASSERT(response->isSucceed(), "response failed");
    
    //Json取得
    std::vector<char>* buffer = response->getResponseData();
    char * json = (char *) malloc(buffer->size() + 1);
    std::string s2(buffer->begin(), buffer->end());
    strcpy(json, s2.c_str());
    picojson::parse(response_data, json, json + strlen(json), &err);
    
    CCASSERT(err.empty(), err.c_str());
    
    picojson::object& values = response_data.get<picojson::object>();
    
    //id
    auto id = Value(values["id"].get<double>());
    CCLOG("%d", id.asInt());
    
    //title
    auto title = Value(values["title"].get<std::string>());
    CCLOG("%s", title.asString().c_str());
    
    //is_bool
    auto is_bool = Value(values["is_bool"].get<bool>());
    CCLOG("%s", is_bool.asString().c_str());
}

ログはこんな感じ

f:id:raharu0425:20140509111942p:plain

とりあえず成功他のアプリとかは通信系の処理どうしてるのかなー