简体   繁体   English

将标头添加到Rails中的请求中

[英]Add headers to a request in rails

I'm using Rails 3.2.1 to make an HTTP Post. 我正在使用Rails 3.2.1进行HTTP发布。

I need to add X-FORWARDED FOR to the header. 我需要将X-FORWARDED FOR添加到标题中。 How do I do that in Rails? 如何在Rails中做到这一点?

Code: 码:

post_data = {
  "username" => tabuser
}

response = Net::HTTP.post_form(URI.parse("http://<my php file>"), post_data)

I find this more readable 我觉得这更具可读性

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

stolen from http://www.dzone.com/snippets/send-custom-headers-rub http://www.dzone.com/snippets/send-custom-headers-rub被盗

HOWEVER !! 但是!

if you want to send 'Accept' header ( Accept: application/json ) to Rails application, you cannot do: 如果您想将'Accept'标头( Accept: application/json )发送到Rails应用程序,则不能执行以下操作:

req.add_field("Accept", "application/json")

but do: 但是:

req['Accept'] = 'application/json'

The reason for this that Rails ignores the Accept header when it contains “,/” or “/,” and returns HTML (which add_field adds). 这样做的原因是,Rails在包含“,/”或“ /”的情况下会忽略Accept标头并返回HTML(由add_field添加)。 This is due to really old browsers sending incorrect "Accept" headers. 这是由于真正的旧版浏览器发送了不正确的“ Accept”标头。

It can be set on the request object: 可以在请求对象上设置它:

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) }

See these Net::HTTP examples: 请参阅以下Net :: HTTP示例:

https://github.com/augustl/net-http-cheat-sheet/blob/master/headers.rb https://github.com/augustl/net-http-cheat-sheet/blob/master/headers.rb

Both answers are ok, but I would add one important thing. 两种答案都可以,但我要补充一件事。 If you are using https you must add line that you use ssl: 如果使用的是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)

Without this use_ssl you will get 'EOFError (end of file reached)'. 没有这个use_ssl,您将得到“ EOFError(到达文件末尾)”。

The original question was for an http post which is what I was looking for. 最初的问题是我正在寻找的http帖子 I'm going to include this solution for others who may be looking: 我将为可能正在寻找的其他人提供此解决方案:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM