I want to do an HTTP POST that looks like an HMTL form posted from a browser. Specifically, post some text fields and a file field.
Posting text fields is straightforward, there's an example right there in the net/http rdocs, but I can't figure out how to post a file along with it.
Net::HTTP doesn't look like the best idea. curb is looking good.
I like RestClient. It encapsulates net/http with cool features like multipart form data:
It also supports streaming.
gem install rest-client
will get you started.Here is my solution after trying other ones available on this post, I'm using it to upload photo on TwitPic:
Fast forward to 2017,
ruby
stdlib
net/http
has this built-in since 1.9.3https://ruby-doc.org/stdlib-2.3.1/libdoc/net/http/rdoc/Net/HTTPHeader.html#method-i-set_form
We can even use
IO
which does not support:size
to stream the form data.Hoping that this answer can really help someone :)
P.S. I only tested this in ruby 2.3.1
restclient did not work for me until I overrode create_file_field in RestClient::Payload::Multipart.
It was creating a 'Content-Disposition: multipart/form-data' in each part where it should be ‘Content-Disposition: form-data’.
http://www.ietf.org/rfc/rfc2388.txt
My fork is here if you need it: git@github.com:kcrawford/rest-client.git
Ok, here's a simple example using curb.
Another one using only standard libraries:
Tried a lot of approaches but only this was worked for me.