本文介绍了停止ruby http请求修改标题名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在ruby中做一个http请求:

I'm doing an http request in ruby:

  http = Net::HTTP.new(uri.host, uri.port)
  req = Net::HTTP::Post.new(uri.path)
  req.body = payload
  req['customeheader'] = 'xxxxxxxxx'
  http.set_debug_output $stdout

我已打开调试,当请求发布时我可以看到标题发布为:

I have debug switched on and when the request is posted I can see the header is being posted as:

  Customheader: xxxxxxxxx

无论如何要阻止这一点,我发布的第三方服务器发出错误是因为标题名称不正确 - 它期待 customheader :

Is there anyway to stop this, the third party server I'm posting to is giving an error because the header name isn't correct - it's expecting customheader:

推荐答案

根据HTTP规范(RFC 2616),标题字段名称。因此,第三方服务器的实现方式已经破裂。

According to the HTTP spec (RFC 2616), header field names are case-insensitive. So the third-party server has a broken implementation.

如果你真的需要,你可以通过猴子补丁Net :: HTTP保留大小写,因为它会使字段下降存储它们时的名称,然后用初始大写字母写它们。

If you really needed to, you could monkey-patch Net::HTTP to preserve case, because it downcases the field names when it stores them and then writes them with initial caps.

这是你使用的存储方法():

Here's the storage method you used (Net::HTTPHeader#[]=):

# File net/http.rb, line 1160
    def []=(key, val)
      unless val
        @header.delete key.downcase
        return val
      end
      @header[key.downcase] = [val]
    end

这里是编写标题的地方():

And here is where it writes the header (Net::HTTPGenericRequest#write_header):

# File lib/net/http.rb, line 2071
    def write_header(sock, ver, path)
      buf = "#{@method} #{path} HTTP/#{ver}\r\n"
      each_capitalized do |k,v|
        buf << "#{k}: #{v}\r\n"
      end
      buf << "\r\n"
      sock.write buf
    end

这些可能是您需要覆盖的唯一方法,但我不是100%肯定。

Those are likely the only methods you'd need to override, but I'm not 100% certain.

这篇关于停止ruby http请求修改标题名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-05 02:42