我需要在一个遗留系统上执行一个非常特定的请求,并发现在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
发布于 2018-06-06 05:26:38
,是查询中的合法字符(此处https://stackoverflow.com/a/31300627/3820185提供了扩展澄清)
用ERB::Util.url_encode代替does取代[^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,你只需要把你的网址传递给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>https://stackoverflow.com/questions/50708934
复制相似问题