2

I am using Net::HTTP::Post to send a request to a pre-determined url, like so:

my_url = '/path/to/static/url' 
my_string_parameter = 'objectName=objectInfo' 
my_other_string_parameter = 'otherObjectName=otherObjectInfo' 

request = Net::HTTP::Post.new(my_url)
request.body = my_string_parameter 

However, I know that my_url expects two string parameters. I have both parameters ready (they're statically generated) to be passed in. Is there a way to pass in multiple strings - both my_string_parameter as well as my_other_string_parameter to a post request via Ruby on Rails?

EDIT: for clarity's sake, I'm going to re-explain everything in a more organized fashion. Basically, what I have is

my_url = 'path/to/static/url' 
# POST requests made to this url require 2 string parameters, 
# required_1 and required_2 
param1 = 'required_1=' + 'param1_value' 
param2 = 'requred_2=' + 'param2_value' 
request = request.NET::HTTP::Post.new(my_url)

If I try request.body = param1, then as expected I get an error saying "Required String parameter 'required_2' is not present". Same with request.body=param2, the same error pops up saying 'required_1' is not present. I'm wondering if there is a way to pass in BOTH parameters to request.body? Or something similar?

swurv
  • 39
  • 1
  • 5

3 Answers3

1

Try this.

uri = URI('http://www.example.com')
req = Net::HTTP::Post.new(uri)
req.set_form_data('param1' => 'data1', 'param2' => 'data2')

Alternative

uri = URI('http://www.example.com/')
res = Net::HTTP.post_form(uri, 'param1' => 'data1', 'param2' => 'data2')
puts res.body

For more request like Get or Patch you can refer This offical doc.

hgsongra
  • 1,454
  • 15
  • 25
0

You can send it like this.

data = {'params' => ['parameter1', 'parameter2']}
request = Net::HTTP::Post.new(my_url)
request.set_form_data(data)
Pramod
  • 1,376
  • 12
  • 21
  • Hm, this didn't seem to work because the url requires specific names for the parameters, something like param_1_name=param_1_value and param_2_name=param_2_value – swurv Jul 29 '16 at 05:06
  • Please edit the question with the specific requirements. – Pramod Jul 29 '16 at 05:26
0

If your params are string:

url = '/path/to/controller_method' 
my_string_parameter = 'objectName=objectInfo' 
my_other_string_parameter = 'otherObjectName=otherObjectInfo'

url_with_params = "#{url}?#{[my_string_parameter, my_other_string_parameter].join('&')}"

request = Net::HTTP::Post.new(url_with_params)

If your params are hash It would be easier

your_params = {
  'objectName' => 'objectInfo',
  'otherObjectName' => 'otherObjectInfo'
}
url = '/path/to/controller_method'
url_with_params = "#{url}?#{your_params.to_query}"
request = Net::HTTP::Post.new(url_with_params)
Hieu Pham
  • 6,577
  • 2
  • 30
  • 50