no method on use_ssl = true - ruby-on-rails

I'm trying to send post request using rails controller, however i faced issue, when i cant make controller accept use_ssl = true.
Here is my code
require "net/http"
require "uri"
params = {'requestId' => '1',
'merchantId' => 'merchantid'
'version' => '1.0.6',
'locale' => 'en_US',
'externalUserId' => '1234',
'partnerId' => 'partnerid',
'emailAddress' => 'test#email.com',
'deviceDTO' => "{'id' => '123123213', 'deviceType' => 'samsung'}",
'timestamp' => Time.now.strftime('%Y-%m-%dT%H:%M:%S.%L%z')
}
url = URI.parse('https://example.com')
http = Net::HTTP::Post.new(url.host)
http.set_form_data(params)
#http.use_ssl = true
#http.verify_mode = OpenSSL::SSL::VERIFY_PEER
res = Net::HTTP.start(url.hostname, url.port) do |h|
h.request(http)
h.use_ssl = true
h.verify_mode = OpenSSL::SSL::VERIFY_NONE
end
errors are :
NoMethodError: undefined method `use_ssl=' for #<Net::HTTP::Post POST>
NoMethodError: undefined method `verify_mode=' for #<Net::HTTP::Post POST>
UPD
error now
Errno::ECONNRESET: Connection reset by peer

use_ssl is a method in Net::HTTP, you are creating a Net::HTTP::Post object.
You might want to do
url = URI.parse('https://example.com/')
http = Net::HTTP.new(url.host, url.port)
if url.scheme == 'https'
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_PEER
end
http.post(url.path, params)

Related

How to call JDoodle API from local Rails server?

I am calling the JDoodle API with post request from my local machine Rails server with valid id and secrete. I am not getting desired response. Please suggest me if i am doing wrong....
My Ruby function to make api call
def run_Jddodle_API
require 'net/http'
require 'uri'
require 'json'
uri = URI.parse("https://api.jdoodle.com/v1/execute")
request = Net::HTTP::Post.new(uri)
request.content_type = "application/json; charset=UTF-8"
request.body = {
"clientId" => "ddc371fd*************c8efbae",
"clientSecret" => "4ee8e79a225***************************a8ee7f331aeeca603",
"script" => "<?php printf(\"hello RAJA\"); ?>",
"language" => "php",
"versionIndex" => "0"
}.to_json
req_options = { use_ssl: uri.scheme == "https", }
response = Net::HTTP.start(uri.hostname, uri.port, req_options) do |http|
http.request(request)
end
puts response.body
end
And the response is
{"error":"Unauthorized Request","statusCode":401}
try changing this line:
request.content_type = "application/json; charset=UTF-8"
to this:
request.content_type = "application/json"
I changed the code as below and it worked but can't say why.?
require 'uri'
require 'net/http'
require 'net/https'
url = URI("https://api.jdoodle.com/v1/execute")
http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true
request = Net::HTTP::Post.new(url.path)
request["Content-Type"] = 'application/json'
request.body = {
"script" => params[:code],
"language" => params[:lang],
"versionIndex" => params[:version],
"clientId" => "dc37******************efbae",
"clientSecret" => "4ee8e79a225a5525*******************************************"
}.to_json
response = http.request(request)
puts response.read_body`

FCM API Bad Request

I'm trying to push a notification through FCM from my Ruby on Rails project, here is my code:
require 'net/http'
require 'json'
def send_notifications
log = Logger.new("log/notifications.log")
begin
uri = URI.parse("https://fcm.googleapis.com/fcm/send")
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_NONE
key = '...'
hash = {:notification => {:sound => "default", :title => "test", :text => "test", :badge => "0"}, :data => {:targetID => "1", :to => "..."}}
req = Net::HTTP::Post.new(uri.path, {'Content-Type' => 'application/json', 'Authorization' => "key=#{key}"})
req.body = hash.to_json
response = http.request(req)
log.debug("response #{response.body}")
rescue => e
log.debug("failed #{e}")
end
end
I'm getting Bad Request 400 error, and debugging the response body only shows this: "to"
Please help me debug this issue. Thank you

rails error on curl converted to Net::HTTP

I receive the following error when trying to run a curl command converted to Net::HTTP in Rails. The url+params gives me the expected response when I run it on the client side using AJAX but of course this exposes my API key.
Any idea why this error is occurring?
error:
undefined method `empty?' for #<URI::HTTPS:0x00000006552fe8>
curl:
curl -X POST -d "maxRetrieve=1" -d "outputMode=json" -d "url=https://www.whitehouse.gov/the-press-office/2016/03/19/weekly-address-president-obamas-supreme-court-nomination" "https://gateway-a.watsonplatform.net/calls/url/URLGetRelations?apikey=ABC123"
rails code:
require 'net/http'
require 'uri'
require 'json'
url = "https://gateway-a.watsonplatform.net/calls/url/URLGetRelations?apikey=ABC123"
encoded_url = URI.encode(url)
uri = URI.parse(encoded_url)
request = Net::HTTP::Post.new(uri)
request.set_form_data(
"maxRetrieve" => "1",
"outputMode" => "json",
"url" => "https://www.whitehouse.gov/the-press-office/2016/03/19/weekly-address-president-obamas-supreme-court-nomination",
)
response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == "https") do |http|
http.request(request)
end
puts response
Looks like you're using the ruby v1.9.3 so I rewrote your code in the following way:
uri = URI.parse("https://gateway-a.watsonplatform.net/calls/url/URLGetRelations?apikey=ABC123")
args = {
"maxRetrieve" => "1",
"outputMode" => "json",
"url" => "https://www.whitehouse.gov/the-press-office/2016/03/19/weekly-address-president-obamas-supreme-court-nomination",
}
uri.query = URI.encode_www_form(args)
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
request = Net::HTTP::Get.new(uri.request_uri)
response = http.request(request)
puts response.body

Ruby POST with custom headers and body?

I'm trying to POST to Mailchimp in Ruby but I can't get any code working which has custom headers and a body. This is the request I am trying to replicate:
curl --request GET \
--url 'https://<dc>.api.mailchimp.com/3.0/' \
--user 'anystring:<your_apikey>'
but I also have to add a JSON body.
If I run this code:
postData = Net::HTTP.post_form(URI.parse('https://xxx.api.mailchimp.com/3.0/lists/xxx/members/'), { ... }})
puts postData.body
I get a response from Mailchimp that the apikey is missing. How do I add the API key?
Based on these posts:
Ruby request to https - "in `read_nonblock': Connection reset by peer (Errno::ECONNRESET)"
Ruby send JSON request
I tried this:
uri = URI('https://xxx.api.mailchimp.com/3.0/lists/xxxx/members/')
req = Net::HTTP::Post.new(uri, initheader = {'Content-Type' =>'application/json'})
req.basic_auth 'anystring', 'xxxx'
req.body = URI.encode_www_form({ ... }})
response = Net::HTTP.new(uri.hostname, uri.port, :use_ssl => uri.scheme == 'https').start {|http| http.request(req) }
puts "Response #{response.code} #{response.message}:#{response.body}"
but I get the error TypeError (no implicit of Hash into String) on the response = ... line. What is the error referring to and how do I fix it?
UPDATE:
using start instead of new:
response = Net::HTTP.start(uri.hostname, uri.port, :use_ssl => uri.scheme == 'https') {|http| http.request(req) }
I am able to send the request, but I get a 400 response: "We encountered an unspecified JSON parsing error"
I get the same response with the posted answer. here is my JSON:
{'email_address' => 'xxxx#gmail.com', 'status' => 'subscribed', 'merge_fields' => {'FNAME' => 'xxx', 'LNAME' => 'xxx' }
I also tried adding the data like this:
req.set_form_data('email_address' => 'xxxx#gmail.com', 'status' => 'subscribed', 'merge_fields' => {'FNAME' => 'xxx', 'LNAME' => 'xxx' } )
but I get the same JSON parse error
Try this, if it works for you
uri = URI('https://api.mailchimp.com/3.0/lists/xxxx/members/')
Net::HTTP.start(uri.host, uri.port, :use_ssl => uri.scheme == 'https') do |http|
req = Net::HTTP::Post.new(uri)
req['Content-Type'] = 'application/json'
req.basic_auth 'username', 'password'
req.set_form_data('from' => '2005-01-01', 'to' => '2005-03-31')
response = http.request req # Net::HTTPResponse object
end
You need to set form data in post request like
req.set_form_data('from' => '2005-01-01', 'to' => '2005-03-31')
Updates:
Try posting raw data like
json_data = {'from' => '2005-01-01', 'to' => '2005-03-31'}.to_json
req.body = json_data

Parametrized get request in Ruby?

How do I make an HTTP GET request with parameters in Ruby?
It's easy to do when you're POSTing:
require 'net/http'
require 'uri'
HTTP.post_form URI.parse('http://www.example.com/search.cgi'),
{ "q" => "ruby", "max" => "50" }
But I see no way of passing GET parameters as a hash using 'net/http'.
Since version 1.9.2 (I think) you can actually pass the parameters as a hash to the URI::encode_www_form method like this:
require 'uri'
uri = URI.parse('http://www.example.com/search.cgi')
params = { :q => "ruby", :max => "50" }
# Add params to URI
uri.query = URI.encode_www_form( params )
and then fetch the result, depending on your preference
require 'open-uri'
puts uri.open.read
or
require 'net/http'
puts Net::HTTP.get(uri)
Use the following method:
require 'net/http'
require 'cgi'
def http_get(domain,path,params)
return Net::HTTP.get(domain, "#{path}?".concat(params.collect { |k,v| "#{k}=#{CGI::escape(v.to_s)}" }.join('&'))) if not params.nil?
return Net::HTTP.get(domain, path)
end
params = {:q => "ruby", :max => 50}
print http_get("www.example.com", "/search.cgi", params)
require 'net/http' require 'uri'
uri = URI.parse( "http://www.google.de/search" ); params = {'q'=>'cheese'}
http = Net::HTTP.new(uri.host, uri.port)
request = Net::HTTP::Get.new(uri.path)
request.set_form_data( params )
# instantiate a new Request object
request = Net::HTTP::Get.new( uri.path+ '?' + request.body )
response = http.request(request)
puts response.body
I would expect it to work without the second instantiation as it would be the first request-objects or the http-object's job but it worked for me this way.
Net::HTTP.get_print 'localhost', '/cgi-bin/badstore.cgi?searchquery=crystal&action=search&x=11&y=15'
or
uri = URI.parse("http://localhost")
req = Net::HTTP::Get.new("/cgi-bin/badstore.cgi?searchquery=crystal&action=search&x=11&y=15")
http = Net::HTTP.new(uri.host, uri.port)
response = http.start do |http|
http.request(req)
end
Use Excon:
conn = Excon.new('http://www.example.com/search.cgi')
conn.get(:query => { "q" => "ruby", "max" => "50" })
new to stack overflow and I guess I can't comment, but #chris.moose is missing double quotes in his function def. line 5 should be:
return Net::HTTP.get(domain, "#{path}?".concat(params.collect { |k,v| "#{k}=#{CGI::escape(v.to_s)}" }.reverse.join('&'))) if not params.nil?
or here's the whole thing redefined for copy/pasting
require 'net/http'
require 'cgi'
def http_get(domain,path,params)
return Net::HTTP.get(domain, "#{path}?".concat(params.collect { |k,v| "#{k}=#{CGI::escape(v.to_s)}" }.reverse.join('&'))) if not params.nil?
return Net::HTTP.get(domain, path)
end
<3
-mike
This is the easiest way to do it
require 'net/http' require 'uri'
#siteurl = "http://www.google.de/search/#{#yourquery}"
define your query
#yourquery = "whatever"
uri = URI.parse( "#siteurl" );
http = Net::HTTP.new(uri.host, uri.port)
request = Net::HTTP::Get.new(uri.path)
# instantiate a new Request object
request = Net::HTTP::Get.new( uri.path+ '?' + request.body )
response = http.request(request)
puts response.body
Might not be perfect but at least you get the idea.

Resources