开发者

Ruby Net::HTTP::Get and JSON responses

开发者 https://www.devze.com 2023-01-15 02:27 出处:网络
I\'m trying to connect to an API and retrieve the json results with my rails app, however it doesn\'t seem to work.

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

Take for example:

@request = Net::HTTP::Get.n开发者_如何学JAVAew "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.

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


I usually use open-uri

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

`


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

Regards!

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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号