简体   繁体   English

NET:HTTP标头ruby gem

[英]NET:HTTP headers ruby gem

I am trying to use the NET:HTTP gem to add an api-key to http header of a client, but it just doesn't seem to be working for some reason when I try and test it out.Basically the server requires the http header of the client or anything to have http_x_api header in order to serve the request. 我正在尝试使用NET:HTTP gem将api-key添加到客户端的http标头中,但是由于某种原因,当我尝试对其进行测试时,它似乎并没有起作用。基本上,服务器需要使用http客户端的标头或具有http_x_api标头的任何内容,以便处理请求。

Server code 服务器代码

   require 'sinatra'

   before do
     halt 400 if (env['API_KEY']) != 'wow'
  end

   get '/' do
     "boo"
   end

Client code 客户代码

    require 'net/http'
    require 'uri'

    port = ENV['PORT'] || '7474'

    res = Net::HTTP.start('localhost', port )  { |h| h.get('/')} 
    res.add_field('api-key', 'wow')
    res.each_header do |key, value|
      p "#{key} => #{value}"
    end        
    puts (res.code == '200' && res.body == 'boo') ? 'OK' : 'FAIL'

    this the response i get back :=>

   "x-frame-options => sameorigin"
   "x-xss-protection => 1; mode=block"
   "content-type => text/html;charset=utf-8"
   "content-length => 0"
   "connection => keep-alive"
   "server => thin 1.5.0 codename Knife"
   "api-key => wow"
    FAIL

On the server, the HTTP header variables in env are prefixed with HTTP_ , so you need to check env['HTTP_API_KEY'] . 在服务器上, env中的HTTP标头变量以HTTP_为前缀,因此您需要检查env['HTTP_API_KEY'] From the documentation : 文档中

HTTP_ Variables: Variables corresponding to the client-supplied HTTP request headers (ie, variables whose names begin with HTTP_). HTTP_变量:与客户端提供的HTTP请求标头相对应的变量(即,名称以HTTP_开头的变量)。 The presence or absence of these variables should correspond with the presence or absence of the appropriate HTTP header in the request. 这些变量的存在与否应与请求中适当的HTTP标头的存在与否相对应。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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