On Tue, 10 Oct 2006, Andrew Stewart wrote:

> Hello Rubyists,
>
> I am struggling to post data over https and would be grateful for any help.
>
> I know the server works because I can hit it with curl and get the response I 
> expect:
>
> curl -d <url-encoded form data> url
>
> When I try to do the same from my Ruby code the server doesn't like it.
>
> The URL to hit looks like:
>
> https://some.host.com/foo/bar.asp?service=someservice
>
> My code looks like:
>
>  require 'net/https'
>  require 'uri'
>
>  url = <as above>
>  uri = URI.parse(url)
>  request = Net::HTTP.new(uri.host, uri.port)
>  request.use_ssl = true
>  request.verify_mode = OpenSSL::SSL::VERIFY_NONE
>  data = { 'key1'     => 'value1',
>           'key2'          => 'value2',
>           'keyn'          => 'valuen' }.map {|k,v| "#{URI.escape 
> (k.to_s)}=#{URI.escape(v.to_s)}"}.join('&')
>  response = request.post("#{uri.path}?#{uri.query}", data)
>
> When I tried this with curl, I used the value of data as my url-encoded form 
> data and everything was fine.
>
> Any ideas?
>
> Thanks in advance,
> Andy Stewart



fortytwo :/var/www/html > cat form.cgi
#! /usr/local/bin/ruby
require 'cgi'
require 'yaml'
(c=CGI.new).out("type" => "text/plain"){ c.params.to_yaml }



fortytwo :/var/www/html > cat post.rb
require 'cgi'
require 'net/https'
require 'uri'

url = ARGV.shift || "https://fortytwo.merseine.nu/form.cgi"
uri = URI.parse url

data = {
   'key1' => 'value1',
   'key2' => 'value2',
   'keyn' => 'valuen',
}

e = lambda{|x| CGI.escape x}
q = lambda{|h| h.map{|k,v| [e[k], e[v]].join '='}.join('&')}
form = q[data]

class HTTPS < Net::HTTP
   def initialize *a, &b
     super
     self.use_ssl = true
     self.verify_mode = OpenSSL::SSL::VERIFY_NONE
   end
end

HTTPS.start(uri.host, uri.port) do |https|
   res = https.post uri.path, form
   puts res.body
end


fortytwo :/var/www/html > ruby post.rb https://fortytwo.merseine.nu/form.cgi
---
key1:
- value1
key2:
- value2
keyn:
- valuen



-a
-- 
in order to be effective truth must penetrate like an arrow - and that is
likely to hurt. -- wei wu wei