LoginSignup
1
0

More than 5 years have passed since last update.

Cocos2d-xのhttp通信で基本認証を通る方法

Posted at

初めに

Cocos2d-xのHttpRequestで基本認証を通る情報が見当たらず、
少し苦戦したためメモ程度に残しておきたいと思い書きました。

今回Base64エンコードをするために、こちらからコードをお借りしました。
コード内で記述されている

macaron::Base64::Encode(s);

は、お借りしたコードに書かれている関数です。

環境

Cocos2d-x 3.17
Ruby 2.5
Rails 5.2.1

解説

まずRails側でコントローラーに以下を記述し、基本認証をかけました。

hoge_controller.rb
http_basic_authenticate_with name: 'user_name', password: 'user_password' if Rails.env.development? || Rails.env.production?

 
 
基本認証のヘッダーの作成はこんな感じです。
初めにで書いたBase64.hをインクルードするのを忘れないでください。

MyScene.cpp
    std::string s = "user_name:user_password";
    std::string base64 = macaron::Base64::Encode(s);

    std::vector<std::string> headers;
    std::string userPass = "Authorization: Basic " + base64;
    headers.push_back(userPass);

 
作成したヘッダーをHttpRequestにセットして送信すれば基本認証を通ることができます。

MyScene.cpp
    auto request = new network::HttpRequest();
    request->setUrl("URL");
    request->setRequestType(network::HttpRequest::Type::GET);
    //↓ヘッダーをセット
    request->setHeaders(headers);
    request->setResponseCallback(CC_CALLBACK_2(MyScene::callbackHttpRequest, this));

    auto httpClient = network::HttpClient::getInstance();
    httpClient->enableCookies(nullptr);
    httpClient->send(request);
1
0
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
1
0