[英]Add headers to a request in rails
我正在使用Rails 3.2.1進行HTTP發布。
我需要將X-FORWARDED
FOR添加到標題中。 如何在Rails中做到這一點?
碼:
post_data = {
"username" => tabuser
}
response = Net::HTTP.post_form(URI.parse("http://<my php file>"), post_data)
我覺得這更具可讀性
require "net/http"
require "uri"
url = URI.parse("http://www.whatismyip.com/automation/n09230945.asp")
req = Net::HTTP::Get.new(url.path)
req.add_field("X-Forwarded-For", "0.0.0.0")
req.add_field("Accept", "*/*")
res = Net::HTTP.new(url.host, url.port).start do |http|
http.request(req)
end
puts res.body
從http://www.dzone.com/snippets/send-custom-headers-rub被盜
但是!
如果您想將'Accept'標頭( Accept: application/json
)發送到Rails應用程序,則不能執行以下操作:
req.add_field("Accept", "application/json")
但是:
req['Accept'] = 'application/json'
這樣做的原因是,Rails在包含“,/”或“ /”的情況下會忽略Accept標頭並返回HTML(由add_field
添加)。 這是由於真正的舊版瀏覽器發送了不正確的“ Accept”標頭。
可以在請求對象上設置它:
request = Post.new(url)
request.form_data = params
request['X-Forwarded-For'] = '203.0.113.195'
request.start(url.hostname, url.port,
:use_ssl => url.scheme == 'https' ) {|http|
http.request(request) }
請參閱以下Net :: HTTP示例:
https://github.com/augustl/net-http-cheat-sheet/blob/master/headers.rb
兩種答案都可以,但我要補充一件事。 如果使用的是https,則必須添加使用ssl的行:
url = URI.parse('https://someurl.com')
http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true
req = Net::HTTP::Get.new(url.request_uri)
req["header_name"] = header
response = http.request(req)
沒有這個use_ssl,您將得到“ EOFError(到達文件末尾)”。
最初的問題是我正在尋找的http帖子 。 我將為可能正在尋找的其他人提供此解決方案:
require 'net/http'
uri = URI.parse("http://<my php file>")
header = {'X-Forwarded-For': '0.0.0.0'}
# Create the HTTP objects
http = Net::HTTP.new(uri.host, uri.port)
request = Net::HTTP::Post.new(uri.request_uri, header)
# Send the request
response = http.request(request)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.