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"}
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.
Related
In my application, the session hash can contain the keys sort and ratings (in addition to _csrf_token and session_id), depending on what action a user takes. That is, it can contain both of them, either one of them, or neither, depending on what a user does.
Now, I wish to call redirect_to in my application and, at the same time, restore any session information (sort or ratings) the user may have provided.
To do this, I want to insert whatever key-value session has currently got stored (out of sort and ratings) as query parameters in my call to redirect_to. So, the path might look something like /movies?sort=...&ratings=....
I don't know how to write the logic for this. How can I do this? And how do I go about selectively inserting query parameters while calling redirect_to? Is it even possible to do this?
Any help is greatly appreciated. Thank you in advance.
First just compose a hash containing the parameters you want - for example:
opts = session.slice(:sort, :ratings)
.merge(params.slice(:sort, :ratings))
.compact_blank
This example would contain the keys :sort, :ratings with the same keys from the parameters merged on top (taking priority).
You can then pass the hash to the desired path helper:
redirect_to foos_path(**opts)
You can either just pass a trailing hash option or use the params option to explitly set the query string:
irb(main):007:0> app.root_path(**{ sort: 'backwards' })
=> "/?sort=backwards"
irb(main):008:0> app.root_path(params: { ratings: 'XX' })
=> "/?ratings=XX"
irb(main):009:0> app.root_path(params: { })
=> "/"
An empty hash will be ignored.
If your calling redirect_to with a hash instead of a string you can add query string parameters with the params: key:
redirect_to { action: :foo, params: opts }
If you're working with an arbitrary given URL/path and want to manipulate the query string parameters you can use the URI module together with the utilities provided by Rack and ActiveSupport for converting query strings to hashes and vice versa:
uri = URI.parse('/foo?bar=1&baz=2&boo=3')
parsed_query = Rack::Utils.parse_nested_query(uri.query)
uri.query = parsed_query.except("baz").merge(x: 5).to_query
puts uri.to_s # => "/foo?bar=1&boo=3&x=5"
I have a hash of the format
{com: 1234, users: [{nid: 3, sets: [1,2,3,4]}, {nid: 4, sets: [5,6,7,8]}]}
which I am sending to a remote server. I am using the HTTParty gem to do this. The code looks like this
class Api
include HTTParty
attr_accessor :headers
def initialize
#headers = { 'Content-Type' => 'application/json' }
end
def post_com(hsh)
response = self.class.post('some_url', query: hsh, headers: headers, format: :plain)
end
end
When I do
api = Api.new.post_com({com: 1234, users: [{nid: 3, sets: [1,2,3,4]}, {nid: 4, sets: [5,6,7,8]}]}
at the remote server, the hash is being sent in the following format
POST "/some_url?com=1234&users[][nid]=3&users[][sets][]=1&users[][sets][]=2&users[][sets][]=3&users[][sets][]=4&users[][nid]=4&users[][sets][]=5&users[][sets][]=6&users[][sets][]=7&users[][sets][]=8
This means for every entry in set, duplicate characeters users[][sets][] are being sent. In operation, there can be many entries in set, and the result is the server rejects the post as having too many characters.
Is there anyway I can have the hash serialized with far less duplication. For instance if I just do
{com: 1234, users: [{nid: 3, sets: [1,2,3,4]}, {nid: 4, sets: [5,6,7,8]}]}.to_json
I receive
"{\"com\":1234,\"users\":[{\"nid\":3,\"sets\":[1,2,3,4]},{\"nid\":4,\"sets\":[5,6,7,8]}]}"
which has far fewer characters.
HTTParty, by default, converts the :query hash into what it calls 'rails style query parameters':
For a query:
get '/', query: {selected_ids: [1,2,3]}
The default query string looks like this:
/?selected_ids[]=1&selected_ids[]=2&selected_ids[]=3
Since you are doing a POST, it is possible/preferable to send your hash in the body of the request rather than in the query string.
def post_com(hsh)
self.class.post('some_url', body: hsh.to_json, headers: headers, format: :plain)
end
This has the advantage that it doesn't do any transformation of the payload and the query string length limit doesn't apply anyway.
For the record, you can disable the default 'rails style' encoding like this:
class Api
include HTTParty
disable_rails_query_string_format
...
end
You can also roll your own custom query string normalizer by passing a Proc to query_string_normalizer.
I'm currently creating both the client and server app using ActiveResource for web servicing. The client has a long string (:history) that needs a conversion process done by the server.
Here, the client calls the post method on my object which extends ActiveResource::Base
active_resource.post(:convert, {:history => hh, :format => format})
This line errors complaining that the URI is too long:
ActiveResource::ClientError Failed. Response code = 414. Response message = Request-URI Too Large.
What other options do I have for sending "large" data ? Probably looking in the neighborhood of 2000 characters of data for the hh string above.
Thanks!
So the signature for the post method is:
post(custom_method_name, options = {}, body = '')
So, when you do:
active_resource.post(:convert, {:history => hh, :format => format})
It's putting your post variables in the options hash, which comes out in your query string for the post.
What you want to do is:
active_resource.post(:convert, nil, {:history => hh, :format => format}.to_json)
I didn't think post parameters factored into URI length. Are you sure it's the hh string and not the actual URI that active_resource.post is using?
Is there a way to manage URL encoding with ActiveResource? Specifically I am looking for a way to pass an email address as a parameter.
Currently my query fails as the # symbol gets URL encoded to %40, causing the lookup on the remote app to fail.
For example, the following query on the ActiveResource model Person…
Person.all(:from => :remote_find_by_email, :params => {:email => "john#example.com")
Produces the following URL
http://example.com/people/remote_find_by_email.xml?email=john%40example.com
Alternately, is there something the remote app should be doing to decode the parameter before performing the lookup?
UPDATE
Thanks to eks, I added the following method and before filter to the controller on the remote app:
before_filter :cgi_unescape_params, :only => [:remote_find_by_email]
private
def cgi_unescape_params
params.each { |k, v| params[k] = CGI.unescape(v) }
end
Try using CGI::unescape on the remote end, that should take care of any % encoded value. Cheers!
Say I have a string that is a url with params in it:
http://www.google.com/search?hl=en&client=firefox-a&hs=zlX&rls=org.mozilla%3Aen-US%3Aofficial&q=something&cts=1279154269301&aq=f&aqi=&aql=&oq=&gs_rfai=
How can can I form an array of all the params from the string? I'm aware of the params array that you can access but I'm talking about just any arbitrary string, not one part of the request.
Not sure if there is a rails shortcut, but:
url = 'http://www.google.com/search?hl=en&client=firefox-a&hs=zlX&rls=org.mozilla%3Aen-US%3Aofficial&q=something&cts=1279154269301&aq=f&aqi=&aql=&oq=&gs_rfai='
params = CGI.parse(URI.parse(url).query)
#=> {"hs"=>["zlX"], "oq"=>[""], "cts"=>["1279154269301"], "aqi"=>[""], "rls"=>["org.mozilla:en-US:official"], "hl"=>["en"], "aq"=>["f"], "gs_rfai"=>[""], "aql"=>[""], "q"=>["something"], "client"=>["firefox-a"]}
params = CGI.parse(url)
is almost there gives you:
#=> {"hs"=>["zlX"], "oq"=>[""], "cts"=>["1279154269301"], "aqi"=>[""], "rls"=>["org.mozilla:en-US:official"], "aq"=>["f"], "http://www.google.com/search?hl"=>["en"], "gs_rfai"=>[""], "aql"=>[""], "q"=>["something"], "client"=>["firefox-a"]}