How to make a HTTP request using Ruby on Rails?
You can use Ruby's Net::HTTP
class:
require 'net/http'
url = URI.parse('http://www.example.com/index.html')
req = Net::HTTP::Get.new(url.to_s)
res = Net::HTTP.start(url.host, url.port) {|http|
http.request(req)
}
puts res.body
Sending HTTP request using ruby on rails
You could do something like this:
def post_test
require 'net/http'
require 'json'
@host = 'localhost'
@port = '8099'
@path = "/posts"
@body ={
"bbrequest" => "BBTest",
"reqid" => "44",
"data" => {"name" => "test"}
}.to_json
request = Net::HTTP::Post.new(@path, initheader = {'Content-Type' =>'application/json'})
request.body = @body
response = Net::HTTP.new(@host, @port).start {|http| http.request(request) }
puts "Response #{response.code} #{response.message}: #{response.body}"
end
Look up Net::HTTP for more information.
Ruby/Rails: create a custom block/yield for http requests to avoid repetition
You can build your own DSL around this:
class Client
def self.post(&block)
dsl = Dsl.new
dsl.instance_eval(&block)
# build request with data from dsl calls
# and execute request
puts "Making a request to #{dsl.url} with headers #{dsl.headers}"
response = "response" # this would be your http response
if rand > 0.5 # response.success?
dsl.on_success.call(response) if dsl.on_success
else
dsl.on_error.call(response) if dsl.on_error
end
end
end
class Dsl
def initialize
@headers = {}
end
def url(*values)
return @url if values.length == 0
@url = values[0]
end
def headers
@headers.freeze
end
def header(*values)
return @headers[values.first] if values.length == 1
@headers[values[0]] = values[1]
end
def on_success(&block)
return @on_success if !block
@on_success = block
end
def on_error(&block)
return @on_error if !block
@on_error = block
end
end
Client.post do |client|
url "http://somewhere"
header "Kwazy", "Cupcakes"
on_success do |response|
puts "got #{response} which is a success"
end
on_error do |response|
puts "gor #{response} which is an error"
end
end
Obviously the distinction if you are calling a getter/setter via a variadic argument length is a bit special and could also be done by using real setter names (url=
, ...) or by using different getter names (get_url
)
THe somewhat special part is the instance_eval(block)
. It allows to change self
so that the receiver of the methods inside the post
block is not Client
but the Dsl
instance.
This can cause troubles and makes a tad harder to debug. So you could also
yield(dsl)
instead and then pass the dsl as an argument to the block.
Client.post do |dsl|
dsl.url "http://somewhere"
#...
end
Update:
Stefans proposal sounds good as well. I think he meant something like this (or check out his link in the comments):
class DslData
attr_accessor :url
end
class Dsl
attr_reader :dsl_data
def initialize
@dsl_data = DslData.new
end
def url(value)
dsl_data.url = value
end
end
class Client
def self.post
dsl = Dsl.new
dsl.instance_eval(&block)
puts "Url: #{dsl.dsl_data.url}"
end
end
Running a HTTP request with rails
Use this method for HTTP requests:
def api_request(type , url, body=nil, header =nil )
require "net/http"
uri = URI.parse(url)
case type
when :post
request = Net::HTTP::Post.new(uri)
request.body = body
when :get
request = Net::HTTP::Get.new(uri)
when :put
request = Net::HTTP::Put.new(uri)
request.body = body
when :delete
request = Net::HTTP::Delete.new(uri)
end
request.initialize_http_header(header)
#request.content_type = 'application/json'
response = Net::HTTP.start(uri.host, uri.port, :use_ssl => uri.scheme == 'https') {|http| http.request request}
end
Your example will be:
api_request(:get, "https://api.cloud-elements.com/elements/api-v2/hubs/marketing/ping",nil, {"Authorization" => "Element TOKEN, User TOKEN" })
Save to database post,but before check http request in Ruby on Rails
I find want can to do
@test = payment_params[:hammer]
# hammer = ''
# hammer += params[:hammer].to_s
aza = ''
uri = URI("https://blockexplorer.com/api/tx/#{@test}")
How can I make simple http requests within a ruby Shoes GUI application?
The problem for me when I tried to run your code was that the Shoes app couldn't connect locally using localhost
. Instead of using localhost
, use your computer's local IP address.
So just change this:
Net::HTTP.get(URI.parse("http://localhost:3000"))
to this:
Net::HTTP.get(URI.parse("http://10.1.4.123:3000"))
if your computer's local IP is 10.1.4.123
.
To see the error logs that confirm this is happening for you, insert this line at the top of your shoes app: Shoes.show_log
Or simply enter cmd
+/
on a Mac or ctrl
+/
in Windows(?) when you are running your *.rb
file in Shoes.app
For me the error that showed up was:
Connection refused - connect(2) for "::1" port 3000
Related Topics
Restarting a Loop from the Top
How to Remove Rvm (Ruby Version Manager) from My System
How to Track System-Specific Config Files in a Repo/Project
Ruby: What Does 'Require: False' in Gemfile Mean
Ruby Style: How to Check Whether a Nested Hash Element Exists
Test If String Is a Number in Ruby on Rails
Checking If a Variable Is Defined
Find Out If Current Time Is Between Two Times
Understanding the Rails Authenticity Token
Ruby Array Access 2 Consecutive(Chained) Elements At a Time
Rails :Dependent =≫ :Destroy VS :Dependent =≫ :Delete_All
Pg::Error: Select Distinct, Order by Expressions Must Appear in Select List