Ruby中的HTTP.post_form,带有自定义标头

时间:2012-04-04 13:11:05

标签: ruby-on-rails ruby http post

我尝试使用Nets / HTTP来使用POST并放入自定义用户代理。我通常使用open-uri,但它不能POST吗?

我用

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

如何将此更改为自定义标题?

编辑我的查询是:

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

4 个答案:

答案 0 :(得分:7)

您可以尝试这样做,例如:

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)

答案 1 :(得分:4)

您无法使用post_form来执行此操作,但您可以这样做:

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

(阅读net/http documentation了解更多信息)

答案 2 :(得分:2)

我需要将json发布到具有自定义标头的服务器。我看到的其他解决方案对我没用。这是我的解决方案。

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

感谢Mike Ebert的tumblr: http://mikeebert.tumblr.com/post/56891815151/posting-json-with-nethttp

答案 3 :(得分:-1)

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