tags:

views:

38

answers:

1

I needed a to have a multipart http post from one app to another that included a file attachment and a nested params hash. I tried using HTTPClient which worked for the file attachment, however I could not get params to send in a nested format.


data_params = Hash.new
data_params[:params] = Hash.new
data_params[:params][:f] = Hash.new
data_params[:params][:d] = Hash.new
data_params[:params][:d][:name] = "Mich"
data_params[:params][:d][:city] = "Ostin"
data_params[:params][:f][:event] = "Sundance"

http_client = HTTPClient.new
body = data_params[:params]
response = http_client.post('http://localhost:3030/receiver/receive_test_data/', body)

with the receiver app seeing the params as {"d"=>"nameMichcityOstin","f"=>"eventSundance"} (with the hash collapsed into strings on the nested level)

I wonder if this is a limitation on http posts or am I simply doing something wrong. I have worked with JSON before, which I know supports a nested structure, but there I have no idea how to add file attachments. I appreciate any suggestions or alternative methods that would comply with 'best practices' on doing something like this.

A: 

I'm not sure which HTTPClient library you're using so I haven't been able to try this, but what if you use keys like this

data_params[:params]['d[name]'] = "Mich"
data_params[:params]['d[city]'] = "Ostin"

i.e. data_params[:params] is just a one level hash.

and then the receiving application will unpack this into the nested hash that you expect.

mikej
Thank you for the solution. It would be nice to have something that could take in a hash of arbitrary depth and post it. I suppose it would have to be something like an XML post and a separate file post.
fflyer05