簡體   English   中英

Ruby Net :: HTTP :: Get和JSON響應

[英]Ruby Net::HTTP::Get and JSON responses

我正在嘗試連接到API並使用我的rails應用程序檢索json結果,但它似乎不起作用。

舉個例子:

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

當我在瀏覽器中嘗試網址時,它可以正常工作! 我得到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

有什么想法嗎?

我通常使用open-uri

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

`

您需要實際發送請求並檢索響應對象,如下所示:

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

問候!

PS:在使用ruby的HTTP庫時, 這個頁面有一些有用的例子。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM