Tyl*_*itt 14 ruby-on-rails header http
我正在使用Rails 3.2.1制作HTTP Post.
我需要X-FORWARDED
在标题中添加FOR.我如何在Rails中做到这一点?
码:
post_data = {
"username" => tabuser
}
response = Net::HTTP.post_form(URI.parse("http://<my php file>"), post_data)
Run Code Online (Sandbox Code Playgroud)
谢谢
equ*_*nt8 14
我发现这更具可读性
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
Run Code Online (Sandbox Code Playgroud)
从http://www.dzone.com/snippets/send-custom-headers-rub中窃取
不过!!
如果要将"Accept"header(Accept: application/json
)发送到Rails应用程序,则不能执行以下操作:
req.add_field("Accept", "application/json")
但是:
req['Accept'] = 'application/json'
原因是当Rails包含",/"或"/"时忽略Accept标头并返回HTML(add_field
添加).这是因为很老的浏览器发送了不正确的"Accept"标头.
hou*_*se9 10
这些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)
Run Code Online (Sandbox Code Playgroud)
如果没有这个use_ssl,你将得到'EOFError(到达文件末尾)'.
归档时间: |
|
查看次数: |
21697 次 |
最近记录: |