0

I am doing an http get using the url http://localhost/add?add_key[0][key]=1234&add_key[0][id]=1. I have a rails app which gives me a neat params hash {"add_key"=>{"0"=>{"key"=>"1234", "id"=>"1"}}. However when I try to post this to a different server using

new_uri = URI.parse("http://10.10.12.1/test") 
res = Net::HTTP.post_form new_uri,params

The server handling the post is seeing this parameter in the request

{"add_key"=>"0key1234id1"}

Looks like post_form requires a String to String hash. So how do I convert the params hash to

{"add_key[0][key]" => "1234", add_key[0][id]" => "1"}

1 Answer 1

3

From the fine manual:

post_form(url, params)
Posts HTML form data to the specified URI object. The form data must be provided as a Hash mapping from String to String.

So you're right about what params needs to be.

You could grab the parsed params in your controller:

{"add_key"=>{"0"=>{"key"=>"1234", "id"=>"1"}}

and then recursively pack that back to the flattened format that post_form expects but that would be a lot of pointless busy work. An easy way to do this would be to grab the raw URL and parse it yourself with URI.parse and CGI.parse, something like this in your controller:

u = URI.parse(request.url)
p = CGI.parse(u.query)

That will leave you with {"add_key[0][key]" => "1234", "add_key[0][id]" => "1"} in p and then you can hand that p to Net::HTTP.post_form.

Sign up to request clarification or add additional context in comments.

3 Comments

That worked great!! Is there any rails way of redirecting the request to another server?
@Vasu: Nothing comes to mind but I've never had a need for it. I don't know if redirecting to a POST is going to work that well.
If the original request was a POST, do CGI.parse(request.raw_post)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.