Http.Post_Form in Ruby with Custom Headers

HTTP.post_form in Ruby with custom headers

You can try this, for example:

http = Net::HTTP.new('domain.com', 80)
path = '/url'

data = 'form=data&more=values'
headers = {
'Cookie' => cookie,
'Content-Type' => 'application/x-www-form-urlencoded'
}

resp, data = http.post(path, data, headers)

Ruby POST with custom headers and body?

Try this, if it works for you

uri = URI('https://api.mailchimp.com/3.0/lists/xxxx/members/')

Net::HTTP.start(uri.host, uri.port, :use_ssl => uri.scheme == 'https') do |http|
req = Net::HTTP::Post.new(uri)
req['Content-Type'] = 'application/json'
req.basic_auth 'username', 'password'
req.set_form_data('from' => '2005-01-01', 'to' => '2005-03-31')

response = http.request req # Net::HTTPResponse object
end

You need to set form data in post request like

req.set_form_data('from' => '2005-01-01', 'to' => '2005-03-31')

Updates:

Try posting raw data like

json_data = {'from' => '2005-01-01', 'to' => '2005-03-31'}.to_json
req.body = json_data

How to invoke HTTP POST method over SSL in ruby?

You are close, but not quite there. Try something like this instead:

uri = URI.parse("https://auth.api.rackspacecloud.com")
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_NONE
request = Net::HTTP::Post.new("/v1.1/auth")
request.add_field('Content-Type', 'application/json')
request.body = {'credentials' => {'username' => 'username', 'key' => 'key'}}.to_json
response = http.request(request)

This will set the Content-Type header as well as post the JSON in the body, rather than in the form data as your code had it. With the sample credentials, it still fails, but I suspect it should work with real data in there.

Ruby https POST with headers

The problem it was a json. This solve my problem. Anyway, my question was not clear, so the bounty goes to Juri

require 'uri'
require 'net/http'
require 'net/https'
require 'json'

@toSend = {
"date" => "2012-07-02",
"aaaa" => "bbbbb",
"cccc" => "dddd"
}.to_json

uri = URI.parse("https:/...")
https = Net::HTTP.new(uri.host,uri.port)
https.use_ssl = true
req = Net::HTTP::Post.new(uri.path, initheader = {'Content-Type' =>'application/json'})
req['foo'] = 'bar'
req.body = "[ #{@toSend} ]"
res = https.request(req)
puts "Response #{res.code} #{res.message}: #{res.body}"


Related Topics



Leave a reply



Submit