ruby - 使用 HTTParty 时的 URI::InvalidURIError

标签 ruby sinatra httparty

我按照 HTTParty github page 中的示例进行操作并想出了这个:

class MatchHistory
    include HTTParty
    base_uri = "api.steampowered.com/IDOTA2Match_570"

    def initialize
        @options = { query: { key: STEAM_API_KEY } }
    end

    def latest
        self.class.get("/GetMatchHistory/V001", @options)
    end
end

get '/' do 
    history = MatchHistory.new

    history.latest.body
end

我收到以下错误:

URI::InvalidURIError at /
the scheme http does not accept registry part: :80 (or bad hostname?)

但是,当我使用如下所示的更简单的解决方案时,它会很好地返回结果:

class MatchHistory
    def initialize
        @base_uri = "http://api.steampowered.com/IDOTA2Match_570"
    end

    def latest
        HTTParty.get(@base_uri + "/GetMatchHistory/V001/?key=" + STEAM_API_KEY)
    end
end

最佳答案

base_uri 是一个类方法,因此您应该在类中定义它,而不是在初始化程序中。您可以在您提供的链接中的第一个示例中看到它。

class MatchHistory
    include HTTParty

    base_uri "api.steampowered.com/IDOTA2Match_570"

    def initialize
        @options = { query: { key: STEAM_API_KEY } }
    end

    def latest
        self.class.get("/GetMatchHistory/V001", @options)
    end
end

关于ruby - 使用 HTTParty 时的 URI::InvalidURIError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28744658/

相关文章:

ruby - HTTParty 不会在 Ruby 文件中加载

ruby - HTTParty::get 返回什么?

ruby - 尝试使用 httparty(ruby) 从 twitter 获取好友列表

ruby - 使用 Ruby/Puma 的本地 SSL

ruby-on-rails - 如何在插件的 before_save 回调中包含实例方法?

routes - 有人有 Rake 任务来查找 Sinatra 生成的路由吗?

sinatra - 如何使用 Rack/保护在 Sinatra 中指定源白名单选项

ruby - 在 ruby 中减去日期

ruby - 格式化数据哈希的最有效方法?

mysql - Sinatra 的 REST API 路由无法正常工作