【问题标题】:ASCII ruby net/http changing request uriASCII ruby​​ net/http 更改请求 uri
【发布时间】:2018-11-15 11:06:11
【问题描述】:

我需要在遗留系统上执行一个非常具体的请求,并发现在获取请求期间,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

【问题讨论】:

    标签: ruby httparty net-http open-uri faraday


    【解决方案1】:

    , 是查询中的合法字符(扩展说明在这里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,你可以将你的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>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-08-02
      • 1970-01-01
      • 2020-04-29
      • 1970-01-01
      • 2014-04-30
      • 1970-01-01
      • 2011-12-10
      相关资源
      最近更新 更多