Ruby Net :: HTTP :: Get和JSON响应

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

举个例子:

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

当我在浏览器中尝试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 

有什么想法吗?

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

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

问候!

PS:在使用ruby的HTTP库时, 这个页面有一些有用的例子。

我通常使用open-uri

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

`