Ruby Net::HTTP::Get 和 JSON 响应 [英] Ruby Net::HTTP::Get and JSON responses

查看:40
本文介绍了Ruby Net::HTTP::Get 和 JSON 响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to connect to an API and retrieve the json results with my rails app, however it doesn't seem to work.

举个例子:

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

当我在浏览器中尝试 url 时,它起作用了!我得到了 JSON 数据,但是当我在 Ruby 中尝试时,主体为零.

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.

>> 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

有什么想法吗?

推荐答案

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

You need to actually send the 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

问候!

PS:在使用 ruby​​ 的 HTTP 库时,这个页面有一些有用的示例.

PS: While using ruby's HTTP lib, this page has some useful examples.

这篇关于Ruby Net::HTTP::Get 和 JSON 响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆