簡體   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