2. サンプルコード

Ruby


require 'rubygems'
require 'net/http'
require 'nkf'
require 'cgi'
require 'logger'

$KCODE = 'utf8'

class Sample

    @@session_key = ""
    @@api_host = "api.adlantis.jp"
    @@api_port = "80"
    @@base_url = "http://#{@@api_host}:#{@@api_port}"
    @@format = "xml"
    @@username = "YOUR_USERNAME"
    @@password = "YOUR_PASSWORD"

    #
    #== Run sample program
    #
    def call_api
      @logger = Logger::new(STDOUT)
      @logger.level = Logger::DEBUG

      Net::HTTP.start(@@api_host, @@api_port) {|http|
        # login
        do_request(http, 'base/login', {'user_name' => @@username, 'password' => @@password}, 'POST')
        if @@session_key == ""
            @logger.error(%!login failed.!)
            exit(1)
        end

        headers = {"cookie" => "_adlantis_session=#{@@session_key};"}

        # get zone list
        zones = do_request(http, 'mobile/zone/list', {'page' => '1', 'per_page' => '5'}, 'GET', headers)

        # logout
        do_request(http, 'base/logout', {}, 'POST')
      }
    end

    #
    #== Make API call
    #
    def do_request(_http, _action, _params, _method, _headers = nil)
      base_url = %!#{@@base_url}/api/#{_action}.#{@@format}!
      @logger.info(%!base_url : #{base_url}!)

      request_params = []
      _params.each_pair do |k, v|
        request_params << %!#{k}=#{v}!
        @logger.info(%!param #{k} => #{v}!)
      end

      case _method
      when "GET"
        response, body = _http.get(%!#{base_url}?#{request_params.join('&')}!, _headers)
      when "POST"
        response, body = _http.post(%!#{base_url}!, request_params.join('&'), _headers)
      end

      body = NKF.nkf('-w --numchar-input', body)

      @logger.info(body)

      if _action == "base/login" && response.header["set-cookie"] && /_adlantis_session=([0-9a-zA-Z]*)/ =~ response.header["set-cookie"]
        @@session_key = $1
      end
    
      return body
    end
end

Sample.new.call_api
Comments