LoginSignup
11
12

More than 5 years have passed since last update.

picojsonを使用してHTTP(POST)通信する

Posted at

picojsonを使用して、JSONフォーマットのデータをPOSTでサーバーに送信します。

POST送信
auto request = new cocos2d::network::HttpRequest();
request->setUrl("http://xxxx/login.php");
request->setRequestType(cocos2d::network::HttpRequest::Type::POST);
request->setResponseCallback(CC_CALLBACK_2(LoginScene::callbackHttpRequest, this));
request->setTag("Login");

picojson::object obj;
obj.insert(make_pair("account_name", picojson::value(m_pEditBoxAccountName->getText())));
obj.insert(make_pair("password", picojson::value(m_pEditBoxPassword->getText())));

picojson::value val(obj);
std::string json = val.serialize();
request->setRequestData(json.c_str(), json.length());

auto httpClient = cocos2d::network::HttpClient::getInstance();
httpClient->enableCookies(nullptr);
httpClient->send(request);

サーバーでは、POSTされた生データをJSONフォーマットにデコードします。

サーバ側PHP
<?php
$postData = file_get_contents("php://input");
$inputData = json_decode(stripcslashes($postData));

// テスト(送信データをそのまま返す).
header('Content-type:application/json');
echo json_encode($inputData);

picojsonでサーバーからのJSONデータを取得します。

受信
void LoginScene::callbackHttpRequest(cocos2d::network::HttpClient *sender, cocos2d::network::HttpResponse *response)
{
    if (response->isSucceed()) {
        // dump data.
//      std::vector<char> *buffer = response->getResponseData();
//      printf("Http Test, dump data: ");
//      for (unsigned int i = 0; i < buffer->size(); i++)
//      {
//          printf("%c", (*buffer)[i]);
//      }
//      printf("\n");

        // json.
        std::vector<char> *buffer = response->getResponseData();
        const char *data = reinterpret_cast<char *>(&(buffer->front()));
        picojson::value v;
        std::string error;
        picojson::parse(v, data, data + strlen(data), &error);
        CCASSERT(error.empty(), error.c_str());

        picojson::object &obj = v.get<picojson::object>();
        std::string &name = obj["account_name"].get<std::string>();
        std::string &password = obj["password"].get<std::string>();
        CCLOG("name:%s password:%s", name.c_str(), password.c_str());
    }
    else {
        CCLOG("HttpRequest failed");
    }
}

このようにすれば、サーバーとの通信でいろいろできるようになります。

以上

11
12
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
11
12