HTTP.post_form in Ruby with custom headers

2020-03-31 05:22发布

问题:

Im trying to use Nets/HTTP to use POST and put in a custom user agent. I've typically used open-uri but it cant do POST can it?

I use

resp, data = Net::HTTP.post_form(url, query)

How would I change this to throw custom headers in?

Edit my query is:

query = {'a'=>'b'}

回答1:

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)


回答2:

You can't use post_form to do that, but you can do it like this:

uri = URI(url)
req = Net::HTTP::Post.new(uri.path)
req.set_form_data(query)
req['User-Agent'] = 'Some user agent'

res = Net::HTTP.start(uri.hostname, uri.port) do |http|
  http.request(req)
end

case res
when Net::HTTPSuccess, Net::HTTPRedirection
  # OK
else
  res.value
end

(Read the net/http documentation for more info)



回答3:

I needed to post json to a server with custom headers. Other solutions I looked at didn't work for me. Here was my solution that worked.

uri = URI.parse("http://sample.website.com/api/auth")
params = {'email' => 'someemail@email.com'}
headers = {
    'Authorization'=>'foobar',
    'Date'=>'Thu, 28 Apr 2016 15:55:01 MDT',
    'Content-Type' =>'application/json',
    'Accept'=>'application/json'}

http = Net::HTTP.new(uri.host, uri.port)
response = http.post(uri.path, params.to_json, headers)
output = response.body
puts output

Thanks due to Mike Ebert's tumblr: http://mikeebert.tumblr.com/post/56891815151/posting-json-with-nethttp



回答4:

require "net/http"

uri = URI.parse('https://your_url.com')
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
http.ca_path='/etc/pki/tls/certs/'
http.ca_file='/etc/pki/tls/certs/YOUR_CERT_CHAIN_FILE'
http.cert = OpenSSL::X509::Certificate.new(File.read("YOUR_CERT)_FILE"))
http.key = OpenSSL::PKey::RSA.new(File.read("YOUR_KEY_FILE"))

#SSLv3 is cracked, and often not allowed
http.ssl_version = :TLSv1_2

#### This is IMPORTANT
http.verify_mode = OpenSSL::SSL::VERIFY_NONE

#Crete the POST request
request = Net::HTTP::Post.new(uri.request_uri)
request.add_field 'X_REMOTE_USER', 'soap_remote_user'
request.add_field 'Accept', '*'
request.add_field 'SOAPAction', 'soap_action'
request.body = request_payload

#Get Response
response = http.request(request)

#Review Response
puts response.body