Ruby Net::HTTP::Get 和 JSON 响应
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3647221/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Ruby Net::HTTP::Get and JSON responses
提问by JP Silvashy
I'm trying to connect to an API and retrieve the json results with my rails app, however it doesn't seem to work.
我正在尝试连接到 API 并使用我的 rails 应用程序检索 json 结果,但是它似乎不起作用。
Take for example:
举个例子:
@request = Net::HTTP::Get.new "http://example.com/?search=thing&format=json"
When I try the url in my browser it works! and I get JSON data, however when I try that in Ruby the body is nil.
当我在浏览器中尝试 url 时,它起作用了!我得到了 JSON 数据,但是当我在 Ruby 中尝试时,主体为零。
>> 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
Any thoughts?
有什么想法吗?
回答by jordinl
I usually use open-uri
我通常使用 open-uri
require 'open-uri'
content = open("http://your_url.com").read
`
`
回答by Pablo Fernandez
You need to actually sendthe request and retrieve a response object, like this:
您需要实际发送请求并检索响应对象,如下所示:
response = Net::HTTP.get_response("example.com","/?search=thing&format=json")
puts response.body //this must show the JSON contents
Regards!
问候!
PS: While using ruby's HTTP lib, this pagehas some useful examples.
PS:在使用 ruby 的 HTTP 库时,这个页面有一些有用的例子。

