繁体   English   中英

ASCII红宝石网/ http更改请求uri

[英]ASCII ruby net/http changing request uri

我需要一个遗留系统上执行一个非常具体的要求,并发现了一个GET请求在HTTP库正在改变任何%2C, 使用不同的实现,net-http,httparty,faraday和open-uri出现相同的问题

2.5.0 :001 > require 'net/http'
=> true 
2.5.0 :002 > require 'erb'
=> true 
2.5.0 :003 > link = "http://example.com?q=" + ERB::Util.url_encode("Hello, World")
=> "http://example.com?q=Hello%2C%20World" 
2.5.0 :004 > uri = URI(link)
=> #<URI::HTTP http://example.com?q=Hello%2C%20World> 
2.5.0 :005 > res = Net::HTTP.get_response(uri)
=> #<Net::HTTPOK 200 OK readbody=true> 

所有这些看起来都很不错,直到我查看了VCR的实际要求

http_interactions:
  - request:
    method: get
    uri: http://example.com/?q=Hello,%20World
    body:
      encoding: US-ASCII
      string: ''
...

如何将请求保留为http://example.com?q=Hello%2C%20World

,是查询中的合法字符(扩展说明在此处https://stackoverflow.com/a/31300627/3820185

ERB::Util.url_encode而不是替换[^a-zA-Z0-9_\\-.]

# File erb.rb, line 930
def url_encode(s)
  s.to_s.dup.force_encoding("ASCII-8BIT").gsub(/[^a-zA-Z0-9_\-.]/n) {
    sprintf("%%%02X", $&.unpack("C")[0])
  }
end

因此,在执行请求时,很可能会重新解析查询以符合实际标准。

编辑

另外,您根本不需要使用ERB::Util.url_encode ,您只需将URL传递给URI ,它将根据标准适当地对其进行转义。

irb(main):001:0> require 'net/http'
=> true
irb(main):002:0> link = URI 'http://example.com?q=Hello, World'
=> #<URI::HTTP http://example.com?q=Hello,%20World>
irb(main):003:0>

暂无
暂无

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

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