【问题标题】:Ruby Net::HTTP::Get and JSON responsesRuby Net::HTTP::Get 和 JSON 响应
【发布时间】:2011-04-08 12:20:35
【问题描述】:

我正在尝试连接到 API 并使用我的 rails 应用程序检索 json 结果,但它似乎不起作用。

举个例子:

@request = Net::HTTP::Get.new "http://example.com/?search=thing&format=json"

当我在浏览器中尝试 url 时,它可以工作!我得到 JSON 数据,但是当我在 Ruby 中尝试它时,正文是 nil。

>> y @request
--- !ruby/object:Net::HTTP::Get 
body: 
body_stream: 
header: 
  accept: 
  - "*/*"
  user-agent: 
  - Ruby
method: GET
path: http://example.com/?search=thing&format=json
request_has_body: false
response_has_body: true

有什么想法吗?

【问题讨论】:

    标签: ruby-on-rails ruby


    【解决方案1】:

    我通常使用open-uri

    require 'open-uri'
    content = open("http://your_url.com").read
    

    `

    【讨论】:

    【解决方案2】:

    您需要真正发送请求并检索响应对象,如下所示:

    response = Net::HTTP.get_response("example.com","/?search=thing&format=json")
    puts response.body //this must show the JSON contents
    

    问候!

    PS:在使用 ruby​​ 的 HTTP 库时,this page 有一些有用的示例。

    【讨论】:

    • 这很有效,该方法需要两个参数并且没有协议:Net::HTTP.get_response("example.com", "/?search=thing&format=json")
    猜你喜欢
    • 1970-01-01
    • 2015-12-13
    • 2014-09-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-02
    • 1970-01-01
    • 2017-04-20
    相关资源
    最近更新 更多