JP *_*shy 24 ruby ruby-on-rails
我正在尝试连接到API并使用我的rails应用程序检索json结果,但它似乎不起作用.
举个例子:
@request = Net::HTTP::Get.new "http://example.com/?search=thing&format=json"
Run Code Online (Sandbox Code Playgroud)
当我在浏览器中尝试网址时,它可以正常工作!我得到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
Run Code Online (Sandbox Code Playgroud)
有什么想法吗?
jor*_*inl 44
我通常使用open-uri
require 'open-uri'
content = open("http://your_url.com").read
Run Code Online (Sandbox Code Playgroud)
`
Pab*_*dez 40
您需要实际发送请求并检索响应对象,如下所示:
response = Net::HTTP.get_response("example.com","/?search=thing&format=json")
puts response.body //this must show the JSON contents
Run Code Online (Sandbox Code Playgroud)
问候!
PS:在使用ruby的HTTP库时,这个页面有一些有用的例子.